CONTENTS

Chapter 8. JavaBeans™

The official definition of a bean, as given in the JavaBeans specification, is: "A bean is a reusable software component based on Sun's JavaBeans specification that can be manipulated visually in a builder tool."

Once you implement a bean, others can use it in a builder environment such as Forte, JBuilder, VisualAge, or Visual Café to produce applications or applets more efficiently.

We will not tell you in detail how to use those environments—you should refer to the documentation that the vendors provide. This chapter explains what you need to know about beans in order to implement them so that other programmers can use your beans easily.

Why Beans?

Programmers coming from a Windows background (specifically, Visual Basic or Delphi) will immediately know why beans are so important. Programmers coming from an environment where the tradition is to "roll your own" for everything may not understand at once. In our experience, programmers who do not come from a Visual Basic background often find it hard to believe that Visual Basic is one of the most successful examples of reusable object technology. One reason for the popularity of Visual Basic becomes clear if you consider how you build a Visual Basic application. For those who have never worked with Visual Basic, here, in a nutshell, is how you do it:

  1. You build the interface by dropping components (called controls in Visual Basic) onto a form window.

  2. Through property sheets, you set properties of the components such as height, color, or other behavior.

  3. The property sheets also list the events to which components can react. For some of those events, you write short snippets of event handling code.

For example, in Chapter 2 of Volume 1, we wrote a program that displays an image in a frame. It took a over a page of code. Here's what you would do in Visual Basic to create a program with pretty much the same functionality.

  1. Add two controls to a window: an Image control for displaying graphics and a Common Dialog control for selecting a file.

  2. Set the Filter properties of the CommonDialog control so that only files that the Image control can handle will show up. This is done in what Visual Basic calls the Properties window, as shown in Figure 8-1.

    Figure 8-1. The Properties window in Visual Basic for an image application

    graphics/08fig01.gif
     

Now, we need to write the five lines of Visual Basic code that will be activated when the project first starts running. This corresponds to an event called the Form_Load, so the code goes in the Form_Load event procedure. The following code pops up the file dialog box—but only files with the right extension are shown because of how we set the filter property. After the user selects an image file, the code then tells the Image control to display it. All the code you need for this sequence looks like this:

Private Sub Form_Load()
  On Error Resume Next
  CommonDialog1.ShowOpen
  Image1.Picture = LoadPicture(CommonDialog1.FileName)
End Sub

That's it. The layout activity, combined with these five lines of code, give essentially the same functionality as a page of Java programming language code. Clearly, it is a lot easier to learn how to drop down components and set properties than it is to write a page of code.

The point is that right now the Java programming language is still a tool used mostly by top-notch, object-oriented programmers. And, realistically, even such programmers are unlikely to be as productive as a good Visual Basic programmer for designing the user interface of a client application. The JavaBeans technology enables vendors to create environments that make it dramatically easier to develop user interfaces for Java applications.

Note that we do not want to imply that Visual Basic is a good solution for every problem. It is clearly optimized for a particular kind of problems—UI-intensive Windows programs. In contrast, Java technology will always have a much wider range of uses. And the good news is that with the advent of JavaBeans technology, some of the benefits of Visual Basic-style application building are on the horizon for programmers. In particular:

  1. Beans with the same functionality as the most common Visual Basic controls are readily available.

  2. Java technology builder tools have come much closer to the ease of use of the Visual Basic environment.

NOTE

graphics/note.gif
 

Once you have built a bean, users of any environment enabled for JavaBeans technology can readily use it. Developers can even, through the magic of the ActiveX bridge technology, deploy JavaBeans in Visual Basic applications and Microsoft Office (see http://java.sun.com/products/javabeans/software).

The Bean-Writing Process

Most of the rest of this chapter shows you the techniques that you will use to write beans. Before we go into details, we give an overview of the process. First, we want to stress that writing a bean is not technically difficult—there are only a few new classes and interfaces for you to master.

In particular, the simplest kind of bean is really nothing more than a Java platform class that follows some fairly strict naming conventions for its event listeners and its methods. Example 8-1 at the end of this section shows the code for an Image Viewer Bean that could give a builder environment based on Java technology the same functionality as the Visual Basic image control that we mentioned in the previous section.

When you look at this code, notice that the ImageViewerBean class really doesn't look any different from any other class. For example, all accessor methods begin with get, all mutator methods begin with set. As you will soon see, builder tools use this standard naming convention to discover properties. For example, fileName is a property of this bean because it has get and set methods.

Note that a property is not the same as an instance variable. In this particular example, the fileName property is computed from the file instance variable. Properties are conceptually at a higher level than instance variables—they are features of the interface, whereas instance variables belong to the implementation of the class.

NOTE

graphics/note.gif
 

For full support in a bean environment, beans should have a default constructor (or no constructor at all, in which case a default constructor is automatically provided), and they should be serializable. This allows the environment to instantiate new beans and to save beans between sessions. However, these are just practical recommendations, not requirements. The ImageViewerBean is serializable because it extends the serializable JLabel class.

One point that you need to keep in mind when you read through the examples in this chapter is that real-world beans are much more elaborate and tedious to code than our brief examples, for two reasons.

  1. Beans need to be usable by less-than-expert programmers. Such people will access most of the functionality of your bean with a visual design tool that uses essentially no programming. You need to expose lots of properties to make it easy to customize the bean behavior.

  2. The same bean needs to be usable in a wide variety of contexts. A bean that is too simplistic to be usable in the real world won't get much respect. Of course, that is why people can charge hundreds of dollars for a professional component, such as a full-featured chart control. For example, at the time of this writing, a popular chart control has

Another good example of a bean with rich behavior is the CalendarBean by Kai Tödter (see Figure 8-2). The bean and its source code are freely available from http://www.toedter.com/en/jcalendar.html. This bean gives users a convenient way of entering dates, simply by locating them in a calendar display. This is obviously pretty complex and not something one would want to program from scratch. By using JavaBeans such as this one, you can take advantage of the work of others, simply by dropping the bean into a builder tool.

Figure 8-2. A Calendar Bean

graphics/08fig02.gif
 

Obviously, a chart or calendar control is about as full-featured a control as one can imagine, but even a bean as simple as a text field for entering numbers turns out to be not quite so simple to code as one might first imagine.

Consider, for example, what should happen as the user types digits into the text field. Should the new numbers be immediately reported to the listeners? On the one hand, this approach is attractive because it gives instant feedback to the user of your bean. But many applications restrict the range for valid entries, and partial entries that can go into an eventual valid entry might not themselves be valid.

For example, suppose a listener wanted to receive only even numbers from the input field. If a user tried to enter 256, the listener would receive an invalid input 25. So, in this case, incremental update is a bad idea because the incremental value could be inappropriate. In cases like this, your bean should report the value to listeners only when the user has finished entering the number, that is, when the user presses ENTER or if the text field loses focus.

If you are writing a program for a single application, then you will simply choose one behavior or the other. But if you are building a bean, you aren't programming for yourself but for a wide audience of users with different needs. Therefore, it would be best to add a property called something like incrementalUpdate and implement both behaviors, depending on the value of that property. Add a few more options like this, and even a simple IntTextBean will end up with a dozen properties.

Fortunately, you need to master only a small number of concepts to write beans with a rich set of behaviors. The example beans in this chapter, while not trivial, are kept simple enough to illustrate the necessary concepts.

TIP

graphics/tip.gif
 

You will find full-featured beans available for sale from many programming product stores, bundled with Java development environments, or for free at sites such as http://www.gamelan.com and the IBM alphaWorks site http://alphaworks.ibm.com.

Example 8-1 ImageViewerBean.java
 1. import java.awt.*;
 2. import java.io.*;
 3. import javax.imageio.*;
 4. import javax.swing.*;
 5.
 6. /**
 7.    A bean for viewing an image.
 8. */
 9. public class ImageViewerBean extends JLabel
10. {
11.
12.    public ImageViewerBean()
13.    {
14.       setBorder(BorderFactory.createEtchedBorder());
15.    }
16.
17.    /**
18.       Sets the fileName property.
19.       @param fileName the image file name
20.    */
21.    public void setFileName(String fileName)
22.    {
23.       try
24.       {
25.          file = new File(fileName);
26.          setIcon(new ImageIcon(ImageIO.read(file)));
27.       }
28.       catch (IOException exception)
29.       {
30.          file = null;
31.          setIcon(null);
32.       }
33.    }
34.
35.    // Use this version for SDK1.3
36.    /*
37.    public void setFileName(String fileName)
38.    {
39.          file = new File(fileName);
40.          Image image
41.             = Toolkit.getDefaultToolkit().getImage(fileName);
42.          MediaTracker tracker = new MediaTracker(this);
43.          tracker.addImage(image, 0);
44.          try { tracker.waitForID(0); } catch (Exception e) {}
45.          setIcon(new ImageIcon(image));
46.          repaint();
47.    }
48.    */
49.
50.    /**
51.          Gets the fileName property.
52.          @return the image file name
53.    */
54.    public String getFileName()
55.    {
56.       if (file == null) return null;
57.       else return file.getPath();
58.    }
59.
60.    public Dimension getPreferredSize()
61.    {
62.       return new Dimension(XPREFSIZE, YPREFSIZE);
63.    }
64.
65.    private File file = null;
66.    private static final int XPREFSIZE = 200;
67.    private static final int YPREFSIZE = 200;
68. }

Using Beans to Build an Application

Before we get into the mechanics of writing beans, we want you to see how you might use or test them. The ImageViewerBean is a perfectly usable bean, but outside a builder environment it can't show off its special features. In particular, the only way to use it in an ordinary program in the Java programming language would be to write code that constructs an object of the bean class, places the object into a container, and calls the setFileName method. That's not rocket science, but it is more code than an overworked programmer may want to write. Builder environments aim to reduce the amount of drudgery that is involved in wiring together components into an application.

Each builder environment uses its own set of strategies to ease the programmer's life. We will cover one environment, the Forte Community Edition. We don't want to claim that Forte is better than other products—in fact, as you will see, it has its share of idiosyncrasies. We simply use Forte because it is a fairly typical programming environment, and because it is freely available.

If you prefer another builder environment, you can still follow the steps of the next sections. The basic principles are the same for most environments. Of course, the details differ.

If you don't want to download a large environment, you can use the BeanBox from Sun Microsystems. The BeanBox is a demonstration of bean capabilities that was designed as a showcase for tool developers. It has advanced features for bean composition, but it doesn't offer any facilities for laying out components nicely. At this point, the BeanBox is somewhat dated—it hasn't been updated since SDK 1.1.

NOTE

graphics/note.gif
 

You can download the Forte Community Edition at no charge from http://www.sun.com/forte/ffj/buy.html. The BeanBox is at http://java.sun.com/products/javabeans/software.

In this example, we will use two beans, ImageViewerBean and FileNameBean. You have already seen the code for the ImageViewerBean. The code for the FileNameBean is a bit more sophisticated. We'll analyze it in depth later in this chapter. For now, all you have to know is that clicking on the button with the "…" label will open a standard File Open dialog box where you can select a file.

Before we can go any further with showing you how to use these beans, we need to explain how to package the bean for import into a builder tool.

Packaging Beans in JAR files

To make any bean usable in a builder tool, package all class files that are used by the bean code into a JAR file. Unlike the JAR files for an applet that you saw previously, a JAR file for a bean needs a manifest file that specifies which class files in the archive are beans and should be included in the Toolbox. For example, here is the manifest file ImageViewerBean.mf for the ImageViewerBean.

Manifest-Version: 1.0

Name: ImageViewerBean.class
Java-Bean: True

Note the blank line between the manifest version and bean name.

If your class is in a package, use slashes to indicate the package, like this:

Name: com/horstmann/beans/ImageViewerBean.class

If your bean contains multiple class files, you only mention in the manifest those class files that are beans and that you want to have displayed in the toolbox. For example, you could place a ImageViewerBean and a FileNameBean into the same JAR file and use the manifest

Manifest-Version: 1.0

Name: ImageViewerBean.class
Java-Bean: True

Name: FileNameBean.class
Java-Bean: True

CAUTION

graphics/caution.gif
 

Some builder tools are extremely fussy about manifests. Make sure that there are no spaces after the ends of each line, that there are blank lines after the version and between bean entries, and that the last line ends in a newline.

To make the JAR file, follow these steps:

  1. Edit the manifest file.

  2. Gather all needed class files in a directory.

  3. Run the jar tool as follows:

    jar cfm JarFile ManifestFile *.class
    

    For example,

    jar cfm ImageViewerBean.jar ImageViewerBean.mf *.class
    

You can also add other items, such as GIF files for icons, to the JAR file. We will discuss bean icons later in this chapter.

CAUTION

graphics/caution.gif
 

Make sure to include all files that your bean needs in the JAR file. In particular, pay attention to inner class files such as ImageViewerBean$1.class.

Builder environments have a mechanism for adding new beans, typically by loading JAR files. Here is what you need to do to import beans into Forte.

Compile the ImageViewerBean and FileNameBean classes and package them into JAR files. Then start Forte and follow these steps.

  1. Select Tools -> Install new Java Bean from the menu.

  2. In the file dialog, move to the ImageViewerBean directory and select ImageViewerBean.jar

  3. Now a dialog pops up that lists all the beans that were found in the JAR file. Select ImageViewerBean.

  4. Finally, you are asked into which palette you want to place the beans. Select "Beans." (There are other palettes for Swing components, AWT components, and so on.)

  5. Have a look at the "Beans" palette. It now contains an icon representing the new bean (see Figure 8-3). However, the icon is just a default icon—you will see later how to add icons to a bean.

    Figure 8-3. Adding a Bean to a Palette in Forte

    graphics/08fig03.gif
     

Repeat this step with the FileNameBean. Now you are ready to compose these beans into an application.

Composing Beans in a Builder Environment

In Forte, select File -> New from the menu. A dialog pops up. Open the "Swing Forms" node of the tree on the left and select JFrame. On the right, specify the name of the frame as ImageViewer (see Figure 8-4).

Figure 8-4. Building a New Form

graphics/08fig04.gif
 

Now you get two windows: a form editor (Figure 8-5) and the familiar code editor (Figure 8-6). The form editor shows the outlines of a border layout, and the code editor contains a few lines of routine code.

Figure 8-5. The Form Editor Window

graphics/08fig05.gif
 

Figure 8-6. The Code Editor Window

graphics/08fig06.gif
 

To add a bean to the form, select the bean in the palette and click on one of the border layout regions.

NOTE

graphics/note.gif
 

Other builders have different user interfaces. For example, you may need to drag the bean to the right place on the form.

Figure 8-7 shows the result of adding an image viewer bean to the center region of the frame.

Figure 8-7. Adding a Bean to a Form

graphics/08fig07.gif
 

If you look into the code editor window, you will find that the source code now contains the Java instructions to add an ImageViewerBean object to the content pane of the frame. The source code is bracketed by dire warnings that you should not edit it. Any edits would be lost when the builder environment updates the code as you modify the form.

NOTE

graphics/note.gif
 

Not all builder environments update source code as you build an application. A builder environment may generate source code when you are done editing, serialize the beans you customized, or perhaps produce an entirely different description of your building activity.

In particular, SDK1.4 has methods for saving and loading XML descriptions of collections of JavaBeans. This technology is still somewhat experimental and mostly of interest to builder tool manufacturers. See http://java.sun.com/products/jfc/tsc/articles/persistence2/index.html for more information on this topic.

Now click on the ImageViewerBean in the form and select View->Properties from the menu. You get a property inspector that lists the bean property names and their current values (see Figure 8-8). This is a vital part of component-based development tools since setting properties at design time is how you set the initial state of a component.

Figure 8-8. A Property Inspector

graphics/08fig08.gif
 

For example, you can modify the text property of the label used for the image bean by simply typing in a new name into the property inspector. Changing the text property is simple—you just edit a string in a text field. Try it out—set the label text to "Hello". The form is immediately updated to reflect your change. When you are done, set the text to the empty string since we don't want text to appear next to the image icon.

NOTE

graphics/note.gif
 

When you change the setting of a property, the Forte environment updates the source code to reflect your action. For example, if you set the text field to Hello, the instruction

imageViewerBean.setText("Hello");

is added to the initComponents method. As already mentioned, other builder tools may have different strategies for recording property settings.

Properties don't have to be strings; they can be values of any Java platform type. To make it possible for users to set values for properties of any type, builder tools access specialized property editors. (Property editors either come with the builder or are supplied by the bean developer. You'll see how to write your own property editors later in this chapter.)

To see a simple property editor at work, look at the background property. The property type is Color. You can see the color editor, with a combo box containing standard color names, and a button labeled "…" that brings up a color dialog (see Figure 8-9).

Figure 8-9. Using a property editor to set properties

graphics/08fig09.gif
 

Go ahead and change the background to orange. Notice that you'll immediately see the change to the background color—the border changes color.

More interestingly, choose a file name for an image file in the property inspector. Once you do so, the ImageViewerBean automatically displays the image (see Figure 8-10).

Figure 8-10. The ImageViewerBean at work

graphics/08fig10.gif
 

NOTE

graphics/note.gif
 

If you look at the property inspector in Figure 8-10, you will find a large number of mysterious properties such as focusCycleRoot and iconTextGap. These are inherited from the JLabel superclass. You will see later in this chapter how you can suppress them from the property inspector.

To complete our application, place a FileNameBean at the south end of the frame. Now we want the image to be loaded when the fileName property of the FileNameBean is changed. This happens through a PropertyChange event; we discuss these kinds of events a little later in this chapter.

To react to the event, select the FileNameBean and select the Events tab from its property inspector (see Figure 8-11). Then click on the <none> entry. A dialog appears that shows that there are currently no handlers associated with this event. Click on the Add button of the dialog. You will be prompted for a method name. Type in loadImage.

Figure 8-11. The Events Tab of the Property Inspector

graphics/08fig11.gif
 

Now have a look at the edit window (see Figure 8-12). It now contains additional event handling code and a new method

Figure 8-12. Event Handling Code in The Edit Window

graphics/08fig12.gif
 

private void loadImage(java.beans.PropertyChange evt)
{
   // Add your handling code here
}

Add the following line of code:

imageViewerBean1.setFileName(fileNameBean1.getFileName());

Then compile and execute the application. Click on the button with the "…" label and select an image file. The image is displayed in the image viewer.

This process demonstrates that you can create a Java application from Java beans, by setting properties and providing a small amount of code for event handlers.

Some builder environments, such as the BeanBox, go even further, eliminating the need for writing any code at all. The BeanBox has built-in mechanisms for various common situations, among them:

With the BeanBox, you can build simple applications entirely without programming, just by dragging components onto a form, setting properties, and wiring events to methods or property setters.

By themselves, the mechanisms of the BeanBox are not sufficient to implement sophisticated applications. In contrast, the Forte mechanism allows the programmer to write applications with a mixture of visual manipulation and coding.

The JavaBeans mechanism doesn't attempt to force an implementation strategy on a builder tool. Instead, it aims to supply information about beans to builder tools that can choose to take advantage of the information in one way or another. You will see in the following sections how to program beans so that tools accurately discover that information.

Naming Patterns for Bean Properties and Events

First, we want to stress there is no cosmic beans class that you extend to build your beans. Visual beans directly or indirectly extend the Component class, but nonvisual beans don't have to extend any particular superclass. Remember, a bean is simply any class that can be manipulated in a builder tool. The builder tool does not look at the superclass to determine the bean nature of a class, but it analyzes the names of its methods. To enable this analysis, the method names for beans must follow certain patterns.

NOTE

graphics/note.gif
 

There is a java.beans.Beans class, but all methods in it are static. Extending it would, therefore, be rather pointless, even though you will see it done occasionally, supposedly for greater "clarity." Clearly, since a bean can't extend both Beans and Component, this approach can't work for visual beans. In fact, the Beans class contains methods that are designed to be called by builder tools, for example, to check whether the tool is operating at design time or run time.

Other languages for visual design environments, such as Visual Basic and Delphi, have special keywords such as "Property" and "Event" to express these concepts directly. The designers of the Java specification decided not to add keywords to the language to support visual programming. Therefore, they needed an alternative so that a builder tool could analyze a bean to learn its properties or events. Actually, there are two alternate mechanisms. If the bean writer uses standard naming patterns for properties and events, then the builder tool can use the reflection mechanism to understand what properties and events the bean is supposed to expose. Alternatively, the bean writer can supply a bean information class that tells the builder tool about the properties and events of the bean. We'll start out using the naming patterns because they are easy to use. You'll see later in this chapter how to supply a bean information class.

NOTE

graphics/note.gif
 

Although the documentation calls these standard naming patterns "design patterns," these are really only naming conventions and have nothing to do with the design patterns that are used in object-oriented programming.

The naming pattern for properties is simple: Any pair of methods

public X getPropertyName()
public void setPropertyName(X x)

corresponds to a read/write property of type X.

For example, in our ImageViewerBean, there is only one read/write property (for the file name to be viewed), with the following methods:

public String getFileName()
public void setFileName(String f)

If you have a get method but not an associated set method, you define a read-only property.

Be careful with the capitalization pattern you use for your method names. The designers of the JavaBeans specification decided that the name of the property in our example would be fileName, with a lowercase f, even though the get and set methods contain an uppercase F (getFileName, setFileName). The bean analyzer performs a process called decapitalization to derive the property name. (That is, the first character after get or set is converted to lower case.) The rationale is that this process results in method and property names that are more natural to programmers.

NOTE

graphics/note.gif
 

The get and set methods you create can do more than simply get and set a private data field. Like any Java method, they can carry out arbitrary actions. For example, the setFileName method of the ImageViewerBean class not only sets the value of the fileName data field, but also opens the file and loads the image.

NOTE

graphics/note.gif
 

In Visual Basic, properties also come from get and set methods. (Delphi uses read and write.) But, in both these languages there is a Property keyword so that the compiler doesn't have to second-guess the programmer's intentions by analyzing method names. And using a keyword in those languages has another advantage: Using a property name on the left side of an assignment automatically calls the set method. Using a property name in an expression automatically calls the get method. For example, in Visual Basic you can write

imageBean.fileName = "corejava.gif"

instead of

imageBean.setFileName("corejava.gif");

There is one exception to the get/set naming pattern. Properties that have Boolean values should use an is/set naming pattern, as in the following examples:

public boolean isPropertyName()
public void setPropertyName(boolean b)

For example, an animation might have a property running, with two methods

public boolean isRunning()
public void setRunning(boolean b)

The setRunning method would start and stop the animation. The isRunning method would report its current status.

For events, the naming pattern is even simpler. A bean builder environment will infer that your bean generates events when you supply methods to add and remove event listeners. Suppose your bean generates events of type EventNameEvent. (All events must end in Event.) Then, the listener interface must be called EventNameListener, and the methods to add and remove a listener must be called.

public void addEventNameListener(EventNameListener e)
public void removeEventNameListener(EventNameListener e)

If you look at the code for the ImageViewerBean, you'll see that it has no events to expose. Later, we will see a timer bean that generates TimerEvent objects and has the following methods to manage event listeners:

public void addTimerListener(TimerListener e)
public void removeTimerListener(TimerListener e)

NOTE

graphics/note.gif
 

What do you do if your class has a pair of get and set methods that don't correspond to a property that you want users to manipulate in a property inspector? In your own classes, you can of course avoid that situation by renaming your methods. But if you extend another class, then you inherit the method names from the superclass. This happens, for example, when your bean extends JPanel or JLabel—a large number of uninteresting properties show up in the property inspector. This shows that naming patterns are really a lousy way for designating properties. You will see later in this chapter how you can override the automatic property discovery process by supplying bean information that specifies exactly which methods correspond to properties.

Bean Property Types

A sophisticated bean will have lots of different kinds of properties that it should expose in a builder tool for a user to set at design time or get at run time. It can also trigger both standard and custom events. Properties can be as simple as the fileName property that you saw in the ImageViewerBean and the FileNameBean or as sophisticated as a color value or even an array of data points—we encounter both of these cases later in this chapter. Furthermore, properties can fire events, as you will see in this section.

Getting the properties of your beans right is probably the most complex part of building a bean because the model is quite rich. The JavaBeans specification allows four types of properties, which we illustrate by various examples.

Simple Properties

A simple property is one that takes a single value such as a string or a number. The fileName property of the ImageViewer is an example of a simple property. Simple properties are easy to program: just use the set/get naming convention we indicated earlier. For example, if you look at the code in Example 8-1, you can see that all it took to implement a simple string property is:

public void setFileName(String f)
{
   fileName = f;
   image = . . .
   repaint();
}
public String getFileName()
{
   if (file == null) return null;
   else return file.getPath();
}

Notice that, as far as the JavaBeans specification is concerned, we also have a read-only property of this bean because we have a method with this signature inside the class

public Dimension getPreferredSize()

without a corresponding setPreferredSize method. You would not normally be able to see read-only properties at design time in a property inspector.

Indexed Properties

An indexed property is one that gets or sets an array. A chart bean (see below) would use an indexed property for the data points. With an indexed property, you supply two pairs of get and set methods: one for the array and one for individual entries. They must follow the pattern:

X[] getPropertyName()
void setPropertyName(X[] x)
X getPropertyName(int i)
void setPropertyName(int i, X x)

Here's an example of the indexed property we use in the chart bean that you will see later in this chapter.

public double[] getValues() { return values; }
public void setValues(double[] v) { values = v; }
public double getValues(int i) { return values[i]; }
public void setValues(int i, double v) { values[i] = v; }
. . .
private double[] values;

The get/set functions that set individual array entries can assume that i is within the legal range. Builder tools will not call them with an index that is less than 0 or larger than the length of the array. In particular, the

setPropertyName(int i, X[] x)

method cannot be used to grow the array. To grow the array, you must manually build a new array and then pass it to this method:

setPropertyName(X[] x)

As a practical matter, however, the get and set methods can still be called programmatically, not just by the builder environment. Therefore, it is best to add some error checking, after all. For example, here is the code that we really use in the ChartBean class.

public double getValues(int i)
{
   if (0 <= i && i < values.length) return values[i];
   return 0;
}

public void setValues(int i, double value)
{
   if (0 <= i && i < values.length) values[i] = value;
}

NOTE

graphics/note.gif
 

As we write this, neither Forte nor the BeanBox support indexed properties in the property inspector. You will see later in this chapter how to overcome this limitation by supplying a custom property editor for arrays.

Bound Properties

Bound properties tell interested listeners that their value has changed. For example, the fileName property in the FileNameBean is a bound property. When the file name changes, then the ImageViewerBean is automatically notified and it loads the new file.

To implement a bound property, you must implement two mechanisms.

  1. Whenever the value of the property changes, the bean must send a PropertyChange event to all registered listeners. This change can occur when the set method is called or when the program user carries out an action, such as editing text or selecting a file.

  2. To enable interested listeners to register themselves, the bean has to implement the following two methods:

    void addPropertyChangeListener(PropertyChangeListener
     listener)
    void removePropertyChangeListener(PropertyChangeListener
     listener)
    

The java.beans package has a convenience class, called PropertyChangeSupport, that manages the listeners for you. To use this convenience class, your bean must have a data field of this class that looks like this:

private PropertyChangeSupport changeSupport
   = new PropertyChangeSupport(this);

You delegate the task of adding and removing property change listeners to that object.

public void addPropertyChangeListener(PropertyChangeListener
   listener)
{
   changeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener
   listener)
{
   changeSupport.removePropertyChangeListener(listener);
}

Whenever the value of the property changes, use the firePropertyChange method of the PropertyChangeSupport object to deliver an event to all the registered listeners. That method has three parameters: the name of the property, the old value, and the new value. For example,

changeSupport.firePropertyChange("fileName",
   oldValue, newValue);

The values must be objects. If the property type is not an object, then you must use an object wrapper. For example,

changeSupport.firePropertyChange("running",
   new Boolean(false), new Boolean(true));

TIP

graphics/tip.gif
 

If your bean extends any Swing class that ultimately extends the JComponent class, then you do not need to implement the addPropertyChangeListener and removePropertyChangeListener methods. These methods are already implemented in the JComponent superclass.

To notify the listeners of a property change, simply call the firePropertyChange method of the JComponent superclass:

firePropertyChange("propertyName", oldValue, newValue);

For your convenience, that method is overloaded for the types boolean, byte, char, double, float, int, long, and short. If oldValue and newValue belong to these types, you do not need to use object wrappers.

Other beans that want to be notified when the property value changes must implement the PropertyChangeListener interface. That interface contains only one method:

void propertyChange(PropertyChangeEvent event)

The code in the propertyChange method is triggered whenever the property value changes, provided, of course, that you have added the recipient to the property change listeners of the bean that generates the event. The PropertyChange-Event object encapsulates the old and new value of the property, obtainable with

Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();

If the property type is not a class type, then the returned objects are the usual wrapper types. For example, if a boolean property is changed, then a Boolean is returned and you need to retrieve the Boolean value with the booleanValue method.

Thus, a listening object must follow this model:

class Listener
{
   public Listener()
   {
      bean.addPropertyChangeListener(new
         PropertyChangeListener()
         {
            void propertyChange(PropertyChangeEvent event)
            {
               Object newValue = event.getNewValue();
               . . .
            }
         });
   }
   . . .
}

Example 8-2 is the full code for the FileNameBean. Since the FileNameBean extends the JPanel class, we did not have to explicitly use a PropertyChangeSupport object. Instead, we rely on the ability of the JPanel class to manage property change listeners.

Example 8-2 FileNameBean.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.beans.*;
  4. import java.io.*;
  5. import javax.swing.*;
  6.
  7. /**
  8.    A bean for specifying file names.
  9. */
 10. public class FileNameBean extends JPanel
 11. {
 12.    public FileNameBean()
 13.    {
 14.       dialogButton = new JButton("...");
 15.       nameField = new JTextField(30);
 16.
 17.       chooser = new JFileChooser();
 18.       chooser.setCurrentDirectory(new File("."));
 19.
 20.       chooser.setFileFilter(new
 21.          javax.swing.filechooser.FileFilter()
 22.          {
 23.             public boolean accept(File f)
 24.             {
 25.                String name = f.getName().toLowerCase();
 26.                return name.endsWith("." + defaultExtension)
 27.                   || f.isDirectory();
 28.             }
 29.             public String getDescription()
 30.             {
 31.                return defaultExtension + " files";
 32.             }
 33.          });
 34.
 35.       setLayout(new GridBagLayout());
 36.       GridBagConstraints gbc = new GridBagConstraints();
 37.       gbc.weightx = 100;
 38.       gbc.weighty = 100;
 39.       gbc.anchor = GridBagConstraints.WEST;
 40.       gbc.fill = GridBagConstraints.BOTH;
 41.       add(nameField, gbc, 0, 0, 1, 1);
 42.
 43.       dialogButton.addActionListener(
 44.          new ActionListener()
 45.          {
 46.             public void actionPerformed(ActionEvent evt)
 47.             {
 48.                int r = chooser.showOpenDialog(null);
 49.                if(r == JFileChooser.APPROVE_OPTION)
 50.                {
 51.                   File f = chooser.getSelectedFile();
 52.                   try
 53.                   {
 54.                      String name = f.getCanonicalPath();
 55.                      setFileName(name);
 56.                   }
 57.                   catch (IOException exception)
 58.                   {
 59.                   }
 60.                }
 61.             }
 62.          });
 63.       nameField.setEditable(false);
 64.
 65.       gbc.weightx = 0;
 66.       gbc.anchor = GridBagConstraints.EAST;
 67.       gbc.fill = GridBagConstraints.NONE;
 68.       add(dialogButton, gbc, 1, 0, 1, 1);
 69.    }
 70.
 71.    /**
 72.       A convenience method to add a component to given grid bag
 73.       layout locations.
 74.       @param c the component to add
 75.       @param gbc the grid bag constraints to use
 76.       @param x the x grid position
 77.       @param y the y grid position
 78.       @param w the grid width
 79.       @param h the grid height
 80.    */
 81.    public void add(Component c, GridBagConstraints gbc,
 82.       int x, int y, int w, int h)
 83.    {
 84.       gbc.gridx = x;
 85.       gbc.gridy = y;
 86.       gbc.gridwidth = w;
 87.       gbc.gridheight = h;
 88.       add(c, gbc);
 89.    }
 90.
 91.    /**
 92.       Sets the fileName property.
 93.       @param newValue the new file name
 94.    */
 95.    public void setFileName(String newValue)
 96.    {
 97.       String oldValue = nameField.getText();
 98.       nameField.setText(newValue);
 99.       firePropertyChange("fileName", oldValue, newValue);
100.    }
101.
102.    /**
103.       Gets the fileName property.
104.       @return the name of the selected file
105.    */
106.    public String getFileName()
107.    {
108.       return nameField.getText();
109.    }
110.
111.    /**
112.       Sets the defaultExtension property.
113.       @param s the new default extension
114.    */
115.    public void setDefaultExtension(String s)
116.    {
117.       defaultExtension = s;
118.    }
119.
120.    /**
121.       Gets the defaultExtension property.
122.       @return the default extension in the file chooser
123.    */
124.    public String getDefaultExtension()
125.    {
126.       return defaultExtension;
127.    }
128.
129.    public Dimension getPreferredSize()
130.    {
131.       return new Dimension(XPREFSIZE, YPREFSIZE);
132.    }
133.
134.    private static final int XPREFSIZE = 200;
135.    private static final int YPREFSIZE = 20;
136.    private JButton dialogButton;
137.    private JTextField nameField;
138.    private JFileChooser chooser;
139.    private String defaultExtension = "gif";
140. }
java.beans.PropertyChangeListener

graphics/api.gif
 

Parameters: event the property change event
java.beans.PropertyChangeSupport

graphics/api.gif
 

java.beans.PropertyChangeEvent

graphics/api.gif
 

javax.swing.JComponent

graphics/api.gif
 

Constrained Properties

A constrained property is the most interesting of the properties, and also the most complex to implement. Such a property is constrained by the fact that any listener can "veto" proposed changes, forcing it to revert to the old setting.

For example, consider a text field to enter a number, implemented as a bean IntTextBean. A consumer of that number may have restrictions on the value; for example, perhaps the number must be between 0 and 255. Such a restriction would be easy to implement: add a minValue and maxValue to the IntTextBean. However, the restriction may be more complex than that. Perhaps the number should be even. Or, it may depend on another number that also changes. In that case, no simple property of the IntTextBean is able to distinguish good user inputs from bad ones. Instead, the bean should notify its consumers of the new value and give the consumers the chance to veto the change. A property that can be vetoed is called a constrained property.

We will put this concept to use with a range bean (see Figure 8-13). This bean contains two IntTextBean fields to specify the lower and the upper bound of a range. (You might use such a bean in a print dialog where the user can specify the range of pages to be printed.) If the user enters a to value that is less than the current from value (or a from value that is greater than the current to value), then the RangeBean vetoes the change.

Figure 8-13. The range bean

graphics/08fig13.gif
 

In this example, the IntTextBean is the producer of the vetoable event, and the RangeBean is the consumer that may issue a veto.

To build a constrained property, your bean must have the following two methods to let it register VetoableChangeListener objects:

public void addVetoableChangeListener(VetoableChangeListener
   listener);
public void removeVetoableChangeListener(VetoableChangeListener
   listener);

Just as there is a convenience class to manage property change listeners, there is a convenience class, called VetoableChangeSupport, that manages vetoable change listeners. Your bean should contain an object of this class.

private VetoableChangeSupport vetoSupport
   = new VetoableChangeSupport(this);

Adding and removing listeners should be delegated to this object. For example:

public void addVetoableChangeListener(VetoableChangeListener
   listener)
{
   vetoSupport.addVetoableChangeListener(listener);
}
public void removeVetoableChangeListener(VetoableChangeListener
   listener)
{
   vetoSupport.removeVetoableChangeListener(listener);
}

TIP

graphics/tip.gif
 

The JComponent class has some support for constrained properties, but it is not as extensive as that for bound properties. The JComponent class keeps a single listener list for vetoable change listeners, not a separate list for each property. And the fireVetoableChange method is not overloaded for basic types. If your bean extends JComponent and has a single constrained property (as is often the case), then the listener support of the JComponent superclass is entirely adequate, and you do not need a separate VetoableChangeSupport object.

An object that is able to veto changes needs to implement the VetoableChangeListener interface. That interface contains one method:

void vetoableChange(PropertyChangeEvent event)
   throws PropertyVetoException

This method receives a PropertyChangeEvent object, from which it can retrieve the current value and the proposed new value with the getOldValue and getNewValue methods.

Notice that the vetoableChange method throws an exception. A listener indicates its disapproval with the proposed change by throwing a PropertyVetoException. This exception forces the bean that produced the event to abandon the new value.

To see how to implement the VetoableChangeListener interface, look at the code for the RangeBean class. It attaches listeners to the from and to bean. Here is the code for the from listener:

public void vetoableChange(PropertyChangeEvent event)
   throws PropertyVetoException
{
   int v = ((Integer)event.getNewValue()).intValue();
   if (v > to.getValue())
      throw new PropertyVetoException("from > to", event);
}

It is highly recommended that constrained properties also be bound properties. That is, your bean should have methods to add PropertyChangeListener objects in addition to VetoableChangeListener objects. You saw how to implement those methods in the preceding section.

To update a constrained property value, a bean uses the following two-phase approach:

  1. Notify all vetoable change listeners of the intent to change the property value. (Use the fireVetoableChange method of the VetoableChangeSupport class.)

  2. If none of the vetoable change listeners has thrown a PropertyVetoException, then update the value of the property.

  3. Notify all property change listeners to confirm that a change has occurred.

Here is a typical example from the IntTextBean code.

public void setValue(int v) throws PropertyVetoException
{
   Integer oldValue = new Integer(getValue());
   Integer newValue = new Integer(v);
   vetoSupport.fireVetoableChange("value", oldValue, newValue);
   // survived, therefore no veto
   value = v;
   setText("" + v);
   changeSupport.firePropertyChange("value", oldValue,
      newValue);
}

It is important that you don't change the property value until all the registered vetoable change listeners have agreed with the proposed change. Conversely, a vetoable change listener should never assume that a change that it agrees with is actually happening. The only reliable way to get notified when a change is actually happening is through a property change listener.

Example 8-3 shows the code for the integer text bean that allows its values to be vetoed—it is based on the IntTextField class from Volume 1. Example 8-4 shows the code for the RangeBean. A range bean contains two IntTextBean objects and vetoes the change if it would result in an invalid range.

Note that the integer text field sets a focus listener that tracks focus events. When the text field gains focus, the original value is saved. When it gives up the focus, then the editComplete method is called.

   public IntTextBean(int defval, int size)
   {
      super("" + defval, size);
      addFocusListener(new
         FocusListener()
         {
            public void focusGained(FocusEvent event)
            {
               if (!event.isTemporary())
                  lastValue = getValue();
            }
            public void focusLost(FocusEvent event)
            {
               if (!event.isTemporary())
                  editComplete();
            }
         });
   }

The editComplete method is similar to the setValue method; however, if a property change was vetoed, it restores the original value and resets the focus to the text field.

   public void editComplete()
   {
      Integer oldValue = new Integer(lastValue);
      Integer newValue = new Integer(getValue());
      try
      {
         fireVetoableChange("value", oldValue, newValue);
         // survived, therefore no veto
         firePropertyChange("value", oldValue, newValue);
      }

      catch(PropertyVetoException e)
      {
         // someone didn't like it
         JOptionPane.showMessageDialog(this, "" + e,
            "Input Error", JOptionPane.WARNING_MESSAGE);
         setText("" + lastValue);
         requestFocus();
      }
   }

CAUTION

graphics/caution.gif
 

The requestFocus method does not work for Swing components in JDK 1.2—see bug #4128659 in the "bug parade" at http://developer.java.sun.com for details.

To see the veto mechanism at work, add the range bean to a form. Type a value into the from field that is larger than the value in the to field. Then, click inside the to field. You will see that the contents of the from field instantly revert to the old value.

Here is what happens:

  1. You type a value into the from field.

  2. You click on the to field.

  3. The from field loses focus, and the focus listener of the from field calls the editComplete method.

  4. That method fires a vetoable change.

  5. The to field vetoes the change.

  6. The catch clause in the editComplete method displays a warning dialog (see Figure 8-14), restores the original value, and requests focus.

    Figure 8-14. A Veto Message

    graphics/08fig14.gif
     

Here is another interesting experiment. Rather than editing the values of the text fields, use a property inspector to set the value of the from property to a value that is higher than the to property. You will find that the property inspector won't let you do that. The setFrom method throws a veto exception, and the value is never set. In some builder environments (but not Forte 2.0), the property inspector attaches itself as a veto listener, so that it can give you an error message and restore the old value in the inspector.

Whenever you build a constrained property into your bean, keep in mind that the bean may have multiple listeners, any of which can veto the change. Therefore, a constrained property that isn't bound doesn't make much sense. Listeners need to be notified when a proposed property change has actually been accepted by all listeners. For this reason, we strongly suggest that all your constrained properties be bound.

Example 8-3 IntTextBean.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.beans.*;
  4. import java.io.*;
  5. import javax.swing.*;
  6. import javax.swing.text.*;
  7.
  8. /**
  9.    A bean for editing integer values
 10. */
 11. public class IntTextBean extends JTextField
 12. {
 13.    public IntTextBean()
 14.    {
 15.       super("0", TEXTSIZE);
 16.       setInputVerifier(new IntTextFieldVerifier());
 17.       addActionListener(new
 18.          ActionListener()
 19.          {
 20.             public void actionPerformed(ActionEvent event)
 21.             {
 22.                editComplete();
 23.             }
 24.          });
 25.       addFocusListener(new
 26.          FocusListener()
 27.          {
 28.             public void focusGained(FocusEvent event)
 29.             {
 30.                if (!event.isTemporary())
 31.                   lastValue = getValue();
 32.
 33.             }
 34.             public void focusLost(FocusEvent event)
 35.             {
 36.                if (!event.isTemporary())
 37.                   editComplete();
 38.             }
 39.          });
 40.    }
 41.
 42.    protected Document createDefaultModel()
 43.    {
 44.       return new IntTextDocument();
 45.    }
 46.
 47.    /**
 48.       This method is called when the text field loses
 49.       focus or the user hits Enter.
 50.    */
 51.    public void editComplete()
 52.    {
 53.       Integer oldValue = new Integer(lastValue);
 54.       Integer newValue = new Integer(getValue());
 55.       try
 56.       {
 57.          fireVetoableChange("value", oldValue, newValue);
 58.          // survived, therefore no veto
 59.          firePropertyChange("value", oldValue, newValue);
 60.       }
 61.       catch(PropertyVetoException e)
 62.       {
 63.          // someone didn't like it
 64.          JOptionPane.showMessageDialog(this, "" + e,
 65.             "Input Error", JOptionPane.WARNING_MESSAGE);
 66.          setText("" + lastValue);
 67.          requestFocus();
 68.             // doesn't work in all JDK versions--see bug #4128659
 69.       }
 70.    }
 71.
 72.    /**
 73.       Checks if the contents of this field is a valid integer.
 74.       @return true of the field contents is valid
 75.    */
 76.    public boolean isValid()
 77.    {
 78.       return IntTextDocument.isValid(getText());
 79.    }
 80.
 81.    /**
 82.       Gets the numeric value of the field contents.
 83.       @param the number that the user typed into the field, or
 84.       0 if the field contents is not valid.
 85.    */
 86.    public int getValue()
 87.    {
 88.       try
 89.       {
 90.          return Integer.parseInt(getText());
 91.       }
 92.       catch(NumberFormatException e)
 93.       {
 94.          return 0;
 95.       }
 96.    }
 97.
 98.    /**
 99.       Sets the constrained value property.
100.       @param v the new value
101.    */
102.    public void setValue(int v) throws PropertyVetoException
103.    {
104.       Integer oldValue = new Integer(getValue());
105.       Integer newValue = new Integer(v);
106.       fireVetoableChange("value", oldValue, newValue);
107.       // survived, therefore no veto
108.       setText("" + v);
109.       firePropertyChange("value", oldValue, newValue);
110.    }
111.
112.    public Dimension getPreferredSize()
113.    {
114.       return new Dimension(XPREFSIZE, YPREFSIZE);
115.    }
116.
117.    private int lastValue;
118.    private static final int XPREFSIZE = 50;
119.    private static final int YPREFSIZE = 20;
120.    private static final int TEXTSIZE = 10;
121. }
122.
123. /**
124.    A document that can only hold valid integers or their
125.    substrings
126. */
127. class IntTextDocument extends PlainDocument
128. {
129.    public void insertString(int offs, String str,
130.       AttributeSet a)
131.       throws BadLocationException
132.    {
133.       if (str == null) return;
134.
135.       String oldString = getText(0, getLength());
136.       String newString = oldString.substring(0, offs)
137.          + str + oldString.substring(offs);
138.
139.       if (canBecomeValid(newString))
140.          super.insertString(offs, str, a);
141.    }
142.
143.    /**
144.       A helper function that tests whether a string is a valid
145.       integer
146.       @param s a string
147.       @return true if s is a valid integer
148.    */
149.    public static boolean isValid(String s)
150.    {
151.       try
152.       {
153.          Integer.parseInt(s);
154.          return true;
155.       }
156.       catch(NumberFormatException e)
157.       {
158.          return false;
159.       }
160.    }
161.
162.    /**
163.       A helper function that tests whether a string is a
164.       substring of a valid integer
165.       @param s a string
166.       @return true if s can be extended to a valid integer
167.    */
168.    public static boolean canBecomeValid(String s)
169.    {
170.       return s.equals("") || s.equals("-") || isValid(s);
171.    }
172. }
173.
174. /**
175.    A verifier that checks if the contents of a text component
176.    is a valid integer.
177. */
178. class IntTextFieldVerifier extends InputVerifier
179. {
180.    public boolean verify(JComponent component)
181.    {
182.       String text = ((JTextComponent)component).getText();
183.       return IntTextDocument.isValid(text);
184.    }
185. }
Example 8-4 RangeBean.java
 1. import java.awt.*;
 2. import java.beans.*;
 3. import java.io.*;
 4. import javax.swing.*;
 5.
 6. /**
 7.    A bean with two integer text fields to specify a range
 8.    of values.
 9. */
10. public class RangeBean extends JPanel
11. {
12.    public RangeBean()
13.    {
14.       add(new JLabel("From"));
15.       add(from);
16.       add(new JLabel("To"));
17.       add(to);
18.
19.       from.addVetoableChangeListener(new
20.          VetoableChangeListener()
21.          {
22.             public void vetoableChange(PropertyChangeEvent event)
23.                throws PropertyVetoException
24.             {
25.                int v = ((Integer)event.getNewValue()).intValue();
26.                if (v > to.getValue())
27.                   throw new PropertyVetoException("from > to",
28.                      event);
29.             }
30.          });
31.
32.       to.addVetoableChangeListener(new
33.          VetoableChangeListener()
34.          {
35.             public void vetoableChange(PropertyChangeEvent event)
36.                throws PropertyVetoException
37.             {
38.                int v = ((Integer)event.getNewValue()).intValue();
39.                if (v < from.getValue())
40.                   throw new PropertyVetoException("to < from",
41.                      event);
42.             }
43.          });
44.    }
45.
46.    /**
47.       Sets the from property.
48.       @param v the new lower bound of the range
49.    */
50.    public void setFrom(int v) throws PropertyVetoException
51.    {
52.       from.setValue(v);
53.    }
54.
55.    /**
56.       Gets the from property.
57.       @return the lower bound of the range
58.    */
59.    public int getFrom() { return from.getValue(); }
60.
61.    /**
62.       Sets the to property.
63.       @param v the new upper bound of the range.
64.    */
65.    public void setTo(int v) throws PropertyVetoException
66.    {
67.       to.setValue(v);
68.    }
69.
70.    /**
71.       Gets the to property.
72.       @return the upper bound of the range
73.    */
74.    public int getTo() { return to.getValue(); }
75.
76.    private IntTextBean from = new IntTextBean();
77.    private IntTextBean to = new IntTextBean();
78. }
java.beans.VetoableChangeListener

graphics/api.gif
 

java.beans.VetoableChangeSupport

graphics/api.gif
 

javax.swing.JComponent

graphics/api.gif
 

java.beans.PropertyVetoException

graphics/api.gif
 

Adding Custom Bean Events

When you add a bound or constrained property to a bean, you also enable the bean to fire events whenever the value of that property changes. However, there are other events that a bean can send out, for example,

Unlike the PropertyChangeEvent events, these events belong to custom classes and need to be captured by custom listeners.

Here is how to write a bean that generates custom events. (Please consult Chapter 8 of Volume 1 for more details on event-handling in the Java platform.) Be sure to follow the first two steps precisely or the introspection mechanism will not recognize that you are trying to define a custom event.

  1. Write a class CustomEvent that extends EventObject. (The event name must end in Event in order for a builder to use the naming patterns to find it.)

  2. Write an interface CustomListener with one or more notification methods. Those methods can have any name, but they must have a single parameter of type CustomEvent and return type void.

  3. Supply the following two methods in the bean:

    public void addCustomListener(CustomListener e)
    public void removeCustomListener(CustomListener e)
    

CAUTION

graphics/caution.gif
 

If your event class doesn't extend EventObject, chances are that your code will compile just fine because none of the methods of the EventObject class are actually needed, and none of the various other methods ever try to cast the event objects to the EventObject class. However, your bean will mysteriously fail—the introspection mechanism will not recognize the events.

To implement the methods needed for adding, removing, and delivering custom events, you can no longer rely on convenience classes that automatically manage the event listeners. Instead, you need to collect and manage all the event listeners. As we discussed in Chapter 8 of Volume 1, the EventListenerList is a con-venience class that is designed for this purpose. Because it is possible for a listener object to implement multiple event listener interfaces, an event listener list entry is specified by the class object of the listener interface and the listener object.

Implementing the methods for adding and removing listeners is straightforward:

public void addCustomListener(CustomListener listener)
{
   listenerList.add(CustomListener.class, listener);
}

public void removeCustomListener(CustomListener listener)
{
   listenerList.remove(CustomListener.class, listener);
}

For each method in the listener interface, you should provide a convenience method for event firing.

public void fireMethodName(CustomEvent event)
{
   EventListener[] listeners = listenerList.getListeners(
      CustomListener.class);

   for (int i = 0; i < listeners.length; i++)
   {
      CustomListener listener = (CustomListener)listeners[i];
      listener.methodName(event);
   }
}

That method is not required by the JavaBeans specification—it just makes it easier to send events to all interested listeners.

Now, let's apply this technique to implementing a TimerBean. This bean should send TimerEvent objects to its listeners. (This is a modification of the Timer class from chapter 8 of Volume 1.) Timer events are generated at regular intervals, measured in milliseconds, provided that the running property is set to true. The interval length is determined by the interval property. Examples 8-5 through 8-7 show the code for the following:

Here is how you can test the bean in Forte.

  1. Start a new application based on a JFrame, as previously described. Drop a timer bean into the frame. This is a nonvisual bean—it does not extend the Component class. It shows up in the frame's inspector under the heading "Non-visual Components" (see Figure 8-15).

    Figure 8-15. A Non-visual Bean

    graphics/08fig15.gif
     

  2. Set its running property to true.

  3. Add a scroll pane to the center of the frame. (Look inside the "Swing" tab in the component panel.)

  4. Add a text area inside the scroll pane.

  5. Hook up the timeElapsed event to a method with name updateTextArea and body

    jTextArea1.append(evt + "\n");
    
  6. Compile and run

    You will see messages filling the text area (see Figure 8-16). If the messages don't show up, double-check that you set the running property to true.

    Figure 8-16. Listening to a Custom Event

    graphics/08fig16.gif
     

In the bean box, you can have a slightly more fun display by hooking up a TimerBean with an EventMonitor bean. You can then start and stop the timer by toggling the running property in the property editor.

Here's the complete code for the TimerBean.

Example 8-5 TimerBean.java
  1. import java.io.*;
  2. import java.util.*;
  3. import javax.swing.event.*;
  4.
  5. /**
  6.    A nonvisual bean that sends timer events.
  7. */
  8. public class TimerBean implements Serializable
  9. {
 10.    public TimerBean()
 11.    {
 12.       listenerList = new EventListenerList();
 13.    }
 14.
 15.    /**
 16.        Sets the interval property.
 17.       @param i the interval between timer ticks (in milliseconds)
 18.    */
 19.    public void setInterval(int i) { interval = i; }
 20.
 21.    /**
 22.       Gets the interval property.
 23.       @return the interval between timer ticks (in milliseconds)
 24.    */
 25.    public int getInterval() { return interval; }
 26.
 27.    /**
 28.       Sets the running property.
 29.       @param b true if the timer is running
 30.    */
 31.    public void setRunning(boolean b)
 32.    {
 33.       if (b && runner == null)
 34.       {
 35.          if (interval <= 0) return;
 36.          runner = new
 37.             Thread()
 38.             {
 39.                public void run()
 40.                {
 41.                   try
 42.                   {
 43.                      while (!Thread.interrupted())
 44.                      {
 45.                         Thread.sleep(interval);
 46.                         fireTimeElapsed(new TimerEvent(this));
 47.                      }
 48.                   }
 49.                   catch(InterruptedException e)
 50.                   {
 51.                   }
 52.                }
 53.             };
 54.          runner.start();
 55.       }
 56.       else if (!b && runner != null)
 57.       {
 58.          runner.interrupt();
 59.          runner = null;
 60.       }
 61.    }
 62.
 63.    /**
 64.       Gets the running property.
 65.       @return true if the timer is running
 66.    */
 67.    public boolean isRunning() { return runner != null; }
 68.
 69.    /**
 70.       Adds a timer listener.
 71.       @param listener the listener to add
 72.    */
 73.    public void addTimerListener(TimerListener listener)
 74.    {
 75.       listenerList.add(TimerListener.class, listener);
 76.    }
 77.
 78.    /**
 79.       Removes a timer listener.
 80.       @param listener the listener to remove
 81.    */
 82.    public void removeTimerListener(TimerListener listener)
 83.    {
 84.       listenerList.add(TimerListener.class, listener);
 85.    }
 86.
 87.    /**
 88.       Sends a timer event to all listeners.
 89.       @param event the event to send
 90.    */
 91.    public void fireTimeElapsed(TimerEvent event)
 92.    {
 93.       EventListener[] listeners = listenerList.getListeners(
 94.          TimerListener.class);
 95.
 96.       for (int i = 0; i < listeners.length; i++)
 97.       {
 98.          TimerListener listener = (TimerListener)listeners[i];
 99.          listener.timeElapsed(event);
100.       }
101.    }
102.
103.    private int interval = 1000;
104.    private EventListenerList listenerList;
105.    private Thread runner;
106. }
Example 8-6 TimerListener.java
 1. import java.util.*;
 2.
 3. /**
 4.    An interface for being notified when a timer tick occurs.
 5. */
 6. public interface TimerListener extends EventListener
 7. {
 8.    /**
 9.       This method is called whenever the time between
10.       notifications has elapsed.
11.       @param evt the timer event that contains
12.       the time of notification
13.    */
14.    public void timeElapsed(TimerEvent evt);
15. }
Example 8-7 TimerEvent.java
 1. import java.util.*;
 2.
 3. /**
 4.    A class to describe timer events.
 5. */
 6. public class TimerEvent extends EventObject
 7. {
 8.    /**
 9.       Constructs a timer event.
10.       @param source the event source
11.    */
12.    public TimerEvent(Object source)
13.    {
14.       super(source);
15.       now = new Date();
16.    }
17.
18.    /**
19.       Reports when the event was constructed.
20.       @return the construction date and time
21.    */
22.    public Date getDate()
23.    {
24.       return now;
25.    }
26.
27.    public String toString()
28.    {
29.       return now + ":" + super.toString();
30.    }
31.
32.    private Date now;
33. }

Property Editors

If you add an integer or string property to a bean, then that property is automatically displayed in the bean's property inspector. But what happens if you add a property whose values cannot easily be edited in a text field, for example, a date or a Color? Then, you need to provide a separate component that the user can use to specify the property value. Such components are called property editors. For example, a property editor for a date object might be a calendar that lets the user scroll through the months and pick a date. A property editor for a Color object would let the user select the red, green, and blue components of the color.

Actually, Forte already has a property editor for colors—you saw it in Figure 8-9. Also, of course, there are property editors for basic types such as String (a text field) and boolean (a choice list with values true and false). These property editors are registered with the property editor manager.

The process for supplying a new property editor is slightly involved. First, you create a bean info class to accompany your bean. The bean info is a collection of miscellaneous information about your bean. For example, if you have a property whose type is int or String but whose legal values are restricted in some way, you may not want to use the general-purpose property editor that is supplied by the builder tool. Instead, you can supply a specific editor for a particular property by naming it in the bean info.

The name of the bean info class must be the name of the bean, followed by the word BeanInfo. That class must implement the BeanInfo interface, an interface with eight methods. It is simpler to extend the SimpleBeanInfo class instead. This convenience class has do-nothing implementations for the eight methods. For example,

// bean info class for ChartBean
class ChartBeanBeanInfo
   extends SimpleBeanInfo
{
   . . .
}

To request a specific editor for a particular bean, you override the getPropertyDescriptors method. That method returns an array of PropertyDescriptor objects. You create one object for each property that should be displayed on a property editor, even those for which you just want the default editor.

You construct a PropertyDescriptor by supplying the name of the property and the class of the bean that contains it.

PropertyDescriptor descriptor
   = new PropertyDescriptor("titlePosition", ChartBean.class);

To request a specific editor for the property, you call the setPropertyEditorClass method of the PropertyDescriptor class.

descriptor.setPropertyEditorClass(TitlePositionEditor.class);

Next, you build an array of descriptors for properties of your bean. For example, the chart bean that we discuss in this section has four properties:

Figure 8-17 shows the chart bean. You can see the title on the top. Its position can be set to left, center, or right. The values property specifies the graph values. If the inverse property is true, then the background is colored and the bars of the chart are white. Example 8-8 lists the code for the chart bean; the bean is simply a modification of the chart applet in Volume 1, Chapter 10.

Figure 8-17. The chart bean

graphics/08fig17.gif
 

The code in Example 8-9 shows the ChartBeanBeanInfo class that specifies the property editors for these properties. It achieves the following:

  1. In the static block, the DoubleArrayEditor is registered as an editor for any double[] array.

  2. The getPropertyDescriptors method returns a descriptor for each property. The title and graphColor properties are used with the default editors, that is, the string and color editors that come with the builder tool.

  3. The titlePosition, values, and inverse properties use special editors of type TitlePositionEditor, DoubleArrayEditor and InverseEditor, respectively.

Figure 8-18 shows the resulting property inspector. You'll see in the following sections how to implement these kinds of editors.

Figure 8-18. The property inspector for the chart bean

graphics/08fig18.gif
 

It is also possible to add property editors with the static registerEditor method of the PropertyEditorManager class, setting a property editor for all properties of a given type. Here is an example:

PropertyEditorManager.registerEditor(Date.class,
   CalendarSelector.class);

NOTE

graphics/note.gif
 

You should not call the registerEditor method in your beans—the default editor for a type is a global setting that is properly the responsibility of the builder environment.

You can use the findEditor method in the PropertyEditorManager class to check whether a property editor exists for a given type in your builder tool. That method does the following:

  1. It looks first to see which property editors are already registered with it. (These will be the editors supplied by the builder tool and by calls to the registerEditor method.)

  2. Then, it looks for a class whose name consists of the name of the type plus the word Editor.

  3. If neither lookup succeeds, then findEditor returns null.

For example, if a CalendarSelector class is registered for java.util.Date objects, then it would be used to edit a Date property. Otherwise, a java.util.DateEditor would be searched.

Example 8-8 ChartBean.java
  1. import java.awt.*;
  2. import java.awt.font.*;
  3. import java.awt.geom.*;
  4. import java.util.*;
  5. import java.beans.*;
  6. import java.io.*;
  7. import javax.swing.*;
  8.
  9. /**
 10.    A bean to draw a bar chart.
 11. */
 12. public class ChartBean extends JPanel
 13. {
 14.    public void paint(Graphics g)
 15.    {
 16.       Graphics2D g2 = (Graphics2D)g;
 17.
 18.       if (values == null || values.length == 0) return;
 19.       double minValue = 0;
 20.       double maxValue = 0;
 21.       for (int i = 0; i < values.length; i++)
 22.       {
 23.          if (minValue > getValues(i)) minValue = getValues(i);
 24.          if (maxValue < getValues(i)) maxValue = getValues(i);
 25.       }
 26.       if (maxValue == minValue) return;
 27.
 28.       Dimension d = getSize();
 29.       Rectangle2D bounds = getBounds();
 30.       double clientWidth = bounds.getWidth();
 31.       double clientHeight = bounds.getHeight();
 32.       double barWidth = clientWidth / values.length;
 33.
 34.       g2.setColor(inverse ? color : Color.white);
 35.       g2.fill(bounds);
 36.       g2.setColor(Color.black);
 37.
 38.       Font titleFont = new Font("SansSerif", Font.BOLD, 20);
 39.       FontRenderContext context = g2.getFontRenderContext();
 40.       Rectangle2D titleBounds
 41.          = titleFont.getStringBounds(title, context);
 42.
 43.       double titleWidth = titleBounds.getWidth();
 44.       double y = -titleBounds.getY();
 45.       double x;
 46.       if (titlePosition == LEFT)
 47.          x = 0;
 48.       else if (titlePosition == CENTER)
 49.          x = (clientWidth - titleWidth) / 2;
 50.       else
 51.          x = clientWidth - titleWidth;
 52.
 53.       g2.setFont(titleFont);
 54.       g2.drawString(title, (float)x, (float)y);
 55.
 56.       double top = titleBounds.getHeight();
 57.       double scale = (clientHeight - top)
 58.          / (maxValue - minValue);
 59.       y = clientHeight;
 60.
 61.       for (int i = 0; i < values.length; i++)
 62.       {
 63.          double x1 = i * barWidth + 1;
 64.          double y1 = top;
 65.          double value = getValues(i);
 66.          double height =  value * scale;
 67.          if (value >= 0)
 68.             y1 += (maxValue - value) * scale;
 69.          else
 70.          {
 71.             y1 += (int)(maxValue * scale);
 72.             height = -height;
 73.          }
 74.
 75.          g2.setColor(inverse ? Color.white : color);
 76.          Rectangle2D bar = new Rectangle2D.Double(x1, y1,
 77.             barWidth - 2, height);
 78.          g2.fill(bar);
 79.          g2.setColor(Color.black);
 80.          g2.draw(bar);
 81.       }
 82.    }
 83.
 84.    /**
 85.       Sets the title property.
 86.       @param t the new chart title.
 87.    */
 88.    public void setTitle(String t) { title = t; }
 89.
 90.    /**
 91.       Gets the title property.
 92.       @return the chart title.
 93.    */
 94.    public String getTitle() { return title; }
 95.
 96.    /**
 97.       Sets the indexed values property.
 98.       @param v the values to display in the chart.
 99.    */
100.    public void setValues(double[] v) { values = v; }
101.
102.    /**
103.       Gets the indexed values property.
104.       @return the values to display in the chart.
105.    */
106.    public double[] getValues() { return values; }
107.
108.    /**
109.       Sets the indexed values property.
110.       @param i the index of the value to set
111.       @param value the new value for that index
112.    */
113.    public void setValues(int i, double value)
114.    {
115.       if (0 <= i && i < values.length) values[i] = value;
116.    }
117.
118.    /**
119.       Gets the indexed values property.
120.       @param i the index of the value to get
121.       @return the value for that index
122.    */
123.    public double getValues(int i)
124.    {
125.       if (0 <= i && i < values.length) return values[i];
126.       return 0;
127.    }
128.
129.    /**
130.       Sets the inverse property.
131.       @param b true if the display is inverted (white bars
132.       on colored background)
133.    */
134.    public void setInverse(boolean b) { inverse = b; }
135.
136.    /**
137.       Gets the inverse property.
138.       @return true if the display is inverted
139.    */
140.    public boolean isInverse() { return inverse; }
141.
142.    /**
143.       Sets the titlePosition property.
144.       @param p LEFT, CENTER, or RIGHT
145.    */
146.    public void setTitlePosition(int p) { titlePosition = p; }
147.
148.    /**
149.       Gets the titlePosition property.
150.       @return LEFT, CENTER, or RIGHT
151.    */
152.    public int getTitlePosition() { return titlePosition; }
153.
154.    /**
155.       Sets the graphColor property.
156.       @param c the color to use for the graph
157.    */
158.    public void setGraphColor(Color c) { color = c; }
159.
160.    /**
161.       Gets the graphColor property.
162.       @param c the color to use for the graph
163.    */
164.    public Color getGraphColor() { return color; }
165.
166.    public Dimension getPreferredSize()
167.    {
168.       return new Dimension(XPREFSIZE, YPREFSIZE);
169.    }
170.
171.    private static final int LEFT = 0;
172.    private static final int CENTER = 1;
173.    private static final int RIGHT = 2;
174.
175.    private static final int XPREFSIZE = 300;
176.    private static final int YPREFSIZE = 300;
177.    private double[] values = { 1, 2, 3 };
178.    private String title = "Title";
179.    private int titlePosition = CENTER;
180.    private boolean inverse;
181.    private Color color = Color.red;
182. }
Example 8-9 ChartBeanBeanInfo.java
 1. import java.beans.*;
 2.
 3. /**
 4.    The bean info for the chart bean, specifying the
 5.    property editors.
 6. */
 7. public class ChartBeanBeanInfo extends SimpleBeanInfo
 8. {
 9.    public PropertyDescriptor[] getPropertyDescriptors()
10.    {
11.       try
12.       {
13.          PropertyDescriptor titlePositionDescriptor
14.             = new PropertyDescriptor("titlePosition",
15.                ChartBean.class);
16.          titlePositionDescriptor.setPropertyEditorClass(
17.             TitlePositionEditor.class);
18.          PropertyDescriptor inverseDescriptor
19.             = new PropertyDescriptor("inverse",
20.                ChartBean.class);
21.          inverseDescriptor.setPropertyEditorClass(
22.             InverseEditor.class);
23.          PropertyDescriptor valuesDescriptor
24.             = new PropertyDescriptor("values",
25.                ChartBean.class);
26.          valuesDescriptor.setPropertyEditorClass(
27.             DoubleArrayEditor.class);
28.
29.          return new PropertyDescriptor[]
30.          {
31.             new PropertyDescriptor("title",
32.                ChartBean.class),
33.             titlePositionDescriptor,
34.             valuesDescriptor,
35.             new PropertyDescriptor("graphColor",
36.                ChartBean.class),
37.             inverseDescriptor
38.          };
39.       }
40.       catch(IntrospectionException e)
41.       {
42.          e.printStackTrace();
43.          return null;
44.       }
45.    }
46. }

java.beans.PropertyEditorManager

graphics/api.gif
 

java.beans.PropertyDescriptor

graphics/api.gif
 

java.beans.BeanInfo

graphics/api.gif
 

Writing a Property Editor

Before we begin showing you how to write a property editor, we want to point out that while each property editor works with a value of one specific type, it can nonetheless be quite elaborate. For example, a font property editor (which edits an object of type Font) could show font samples to allow the user to pick a font in a more congenial way.

Next, any property editor you write must implement the PropertyEditor interface, an interface with 12 methods. As with the BeanInfo interface, you will not want to do this directly. Instead, it is far more convenient to extend the convenience PropertyEditorSupport class that is supplied with the standard library. This support class comes with methods to add and remove property change listeners, and with default versions of all other methods of the PropertyEditor interface. For example, our editor for editing the title position of a chart in our chart bean starts out like this:

// property editor class for title position
class TitlePositionEditor
   extends PropertyEditorSupport
{
   . . .
}

Note that if a property editor class has a constructor, it must also supply a default constructor, that is, one without arguments.

Finally, before we get into the mechanics of actually writing a property editor, we want to point out that the editor is under the control of the builder, not the bean. The builder adheres to the following procedure to display the current value of the property:

  1. It instantiates property editors for each property of the bean.

  2. It asks the bean to tell it the current value of the property.

  3. It then asks the property editor to display the value.

The property editor can use either text-based or graphically-based methods to actually display the value. We discuss these methods next.

Simple Property Editors

Simple property editors work with text strings. You override the setAsText and getAsText methods. For example, our chart bean has a property that lets you set where the title should be displayed: Left, Center, or Right. These choices are implemented as integer constants.

private static final int LEFT = 0;
private static final int CENTER = 1;
private static final int RIGHT = 2;

But of course, we don't want them to appear as numbers 0, 1, 2 in the text field—unless we are competing for inclusion in the User Interface Hall of Horrors. Instead, we define a property editor whose getAsText method returns the value as a string. The method calls the getValue method of the PropertyEditor to find the value of the property. Since this is a generic method, the value is returned as an Object. If the property type is a basic type, we need to return a wrapper object. In our case, the property type is int, and the call to getValue returns an Integer.

class TitlePositionEditor
   extends PropertyEditorSupport
{
   public String getAsText()
   {
      int i = ((Integer)getValue()).intValue();
      if (0 <= i && i < options.length) return options[i];
      return "";
   }
   . . .
   private String[] options = { "Left", "Center", "Right" };
}

Now, the text field displays one of these fields. When the user edits the text field, this triggers a call to the setAsText method to update the property value by invoking the setValue method. It, too, is a generic method whose parameter is of type Object. To set the value of a numeric type, we need to pass a wrapper object.

public void setAsText(String s)
{
   for (int i = 0; i < options.length; i++)
   {
      if (options[i].equals(s))
      {
         setValue(new Integer(i));
         return;
      }
   }
}

Actually, this property editor is not a good choice for the titlePosition property, unless, of course, we are also competing for entry into the User Interface Hall of Shame. The user may not know what the legal choices are. It would be better to display all valid settings (see Figure 8-19). The PropertyEditorSupport class gives a simple method to display the selections in a property editor. We simply write a getTags method that returns an array of strings.

Figure 8-19. The TitlePositionEditor at work

graphics/08fig19.gif
 

public String[] getTags() { return options; }

The default getTags method returns null. By returning a non-null value, we indicate a choice field instead of a text field.

We still need to supply the getAsText and setAsText methods. The getTags method simply specifies the values to be displayed in a combo box. The getAsText/setAsText methods translate between the strings and the data type of the property (which may be a string, an integer, or a completely different type).

Example 8-10 lists the complete code for this property editor.

Example 8-10 TitlePositionEditor.java
 1. import java.beans.*;
 2.
 3. /**
 4.    A custom editor for the titlePosition property of the
 5.    ChartBean. The editor lets the user choose between
 6.    Left, Center, and Right
 7. */
 8. public class TitlePositionEditor
 9.    extends PropertyEditorSupport
10. {
11.    public String getAsText()
12.    {
13.       int value = ((Integer)getValue()).intValue();
14.       return options[value];
15.    }
16.
17.    public void setAsText(String s)
18.    {
19.       for (int i = 0; i < options.length; i++)
20.       {
21.          if (options[i].equals(s))
22.          {
23.             setValue(new Integer(i));
24.             return;
25.          }
26.       }
27.    }
28.
29.    public String[] getTags() { return options; }
30.
31.    private String[] options = { "Left", "Center", "Right" };
32. }
java.beans.PropertyEditorSupport

graphics/api.gif
 

GUI-Based Property Editors

More sophisticated property types can't be edited as text. Instead, they are represented in two ways. The property inspector contains a small area (which otherwise would hold a text box or combo box) onto which the property editor will draw a graphical representation of the current value. When the user clicks on that area, a custom editor dialog box pops up (see Figure 8-20). The dialog box contains a component to edit the property values, supplied by the property editor, and various buttons, supplied by the builder environment.

Figure 8-20. A custom editor dialog

graphics/08fig20.gif
 

To build a GUI-based property editor:

  1. Tell the builder tool that you will paint the value and not use a string.

  2. "Paint" the value the user enters onto the GUI.

  3. Tell the builder tool that you will be using a GUI-based property editor.

  4. Build the GUI.

  5. Write the code to validate what the user tries to enter as the value.

For the first step, you override the getAsText method in the PropertyEditor interface to return null and the isPaintable method to return true.

public String getAsText()
{
   return null;
}

public boolean isPaintable()
{
   return true;
}

Then, you implement the paintValue method. It receives a Graphics context and the coordinates of the rectangle inside which you can paint. Note that this rectangle is typically small, so you can't have a very elaborate representation. To graphically represent the inverse property, we draw the string "Inverse" in white letters with a black background, or the string "Normal" in black letters with a white background (see Figure 8-18).

public void paintValue(Graphics g, Rectangle box)
{
   Graphics2D g2 = (Graphics2D)g;
   boolean isInverse = ((Boolean)getValue()).booleanValue();
   String s = isInverse ? "Inverse" : "Normal";
   g2.setColor(isInverse ? Color.black : Color.white);
   g2.fill(box);
   g2.setColor(isInverse ? Color.white : Color.black);
   // compute string position to center string
   . . .
   g2.drawString(s, (float)x, (float)y);
}

Of course, this graphical representation is not editable. The user must click on it to pop up a custom editor.

You indicate that you will have a custom editor by overriding the supportsCustomEditor in the PropertyEditor interface to return true.

public boolean supportsCustomEditor()
{
   return true;
}

Now, you write the code that builds up the component that will hold the custom editor. You will need to build a separate custom editor class for every property. For example, associated to our InverseEditor class is an InverseEditorPanel class (see Example 8-9) that describes a GUI with two radio buttons to toggle between normal and inverse mode. That code is straightforward. However, the GUI actions must update the property values. We did this as follows:

  1. Have the custom editor constructor receive a reference to the property editor object and store it in a variable editor.

  2. To read the property value, we have the custom editor call editor.getValue().

  3. To set the object value, we have the custom editor call editor.setValue(newValue) followed by editor.firePropertyChange().

Next, the getCustomEditor method of the PropertyEditor interface constructs and returns an object of the custom editor class.

public Component getCustomEditor()
{
   return new InverseEditorPanel(this);
}

Example 8-11 shows the complete code for the InverseEditor that displays the current setting in the property inspector. Example 8-12 lists the code implementing the pop-up editor panel.

The other custom editor that we built for the chart bean class lets you edit a double[] array. Recall that neither Forte nor the BeanBox can edit array properties. We developed this custom editor to fill this obvious gap. Figure 8-21 shows the custom editor in action. All array values are shown in the list box, prefixed by their array index. Clicking on an array value places it into the text field above it, and you can edit it. You can also resize the array. The code for the DoubleArrayPanel class that implements the GUI is listed in Example 8-14.

Figure 8-21. The custom editor dialog for editing an array

graphics/08fig21.gif
 

The code for the property editor class (shown in Example 8-13) is almost identical to that of the InverseEditor, except that we simply paint a string consisting of the first few array values, followed by … in the paintValue method. And, of course, we return a different custom editor in the getCustomEditor method. These examples complete the code for the chart bean.

NOTE

graphics/note.gif
 

Unfortunately, we have to paint the array values. It would be more convenient to return a string with the getAsText method. However, some builder environments use a text field whenever the getAsText method returns a non-null string. Those environments won't pop up a custom editor if you click on the text, even if the getCustomEditor method returns an editor component.

Example 8-11 InverseEditor.java
 1. import java.awt.*;
 2. import java.awt.font.*;
 3. import java.awt.geom.*;
 4. import java.beans.*;
 5.
 6. /**
 7.    The property editor for the inverse property of the ChartBean.
 8.    The inverse property toggles between colored graph bars
 9.    and colored background.
10. */
11. public class InverseEditor extends PropertyEditorSupport
12. {
13.    public Component getCustomEditor()
14.    {
15.       return new InverseEditorPanel(this);
16.    }
17.
18.    public boolean supportsCustomEditor()
19.    {
20.       return true;
21.    }
22.
23.    public boolean isPaintable()
24.    {
25.       return true;
26.    }
27.
28.    public void paintValue(Graphics g, Rectangle box)
29.    {
30.       Graphics2D g2 = (Graphics2D)g;
31.       boolean isInverse = ((Boolean)getValue()).booleanValue();
32.       String s = isInverse ? "Inverse" : "Normal";
33.       g2.setColor(isInverse ? Color.black : Color.white);
34.       g2.fill(box);
35.       g2.setColor(isInverse ? Color.white : Color.black);
36.       FontRenderContext context = g2.getFontRenderContext();
37.       Rectangle2D stringBounds = g2.getFont().getStringBounds(
38.          s, context);
39.       double w = stringBounds.getWidth();
40.       double x = box.x;
41.       if (w < box.width) x += (box.width - w) / 2;
42.       double ascent = -stringBounds.getY();
43.       double y = box.y
44.          + (box.height - stringBounds.getHeight()) / 2 + ascent;
45.       g2.drawString(s, (float)x, (float)y);
46.    }
47.
48.    public String getAsText()
49.    {
50.       return null;
51.    }
52. }
Example 8-12 InverseEditorPanel.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import java.text.*;
 4. import java.lang.reflect.*;
 5. import java.beans.*;
 6. import javax.swing.*;
 7.
 8. /**
 9.    The panel for setting the inverse property. It contains
10.    radio buttons to toggle between normal and inverse coloring.
11. */
12. public class InverseEditorPanel extends JPanel
13. {
14.    public InverseEditorPanel(PropertyEditorSupport ed)
15.    {
16.       editor = ed;
17.       ButtonGroup g = new ButtonGroup();
18.       boolean isInverse
19.          = ((Boolean)editor.getValue()).booleanValue();
20.       normal = new JRadioButton("Normal", !isInverse);
21.       inverse = new JRadioButton("Inverse", isInverse);
22.
23.       g.add(normal);
24.       g.add(inverse);
25.       add(normal);
26.       add(inverse);
27.
28.       ActionListener buttonListener =
29.          new ActionListener()
30.          {
31.             public void actionPerformed(ActionEvent event)
32.             {
33.                editor.setValue(
34.                   new Boolean(inverse.isSelected()));
35.                editor.firePropertyChange();
36.             }
37.          };
38.
39.       normal.addActionListener(buttonListener);
40.       inverse.addActionListener(buttonListener);
41.    }
42.
43.    private JRadioButton normal;
44.    private JRadioButton inverse;
45.    private PropertyEditorSupport editor;
46. }
Example 8-13 DoubleArrayEditor.java
 1. import java.awt.*;
 2. import java.awt.font.*;
 3. import java.awt.geom.*;
 4. import java.beans.*;
 5.
 6. /**
 7.    A custom editor for an array of floating point numbers.
 8. */
 9. public class DoubleArrayEditor extends PropertyEditorSupport
10. {
11.    public Component getCustomEditor()
12.    {
13.       return new DoubleArrayEditorPanel(this);
14.    }
15.
16.    public boolean supportsCustomEditor()
17.    {
18.       return true;
19.    }
20.
21.    public boolean isPaintable()
22.    {
23.       return true;
24.    }
25.
26.    public void paintValue(Graphics g, Rectangle box)
27.    {
28.       Graphics2D g2 = (Graphics2D)g;
29.       double[] values = (double[]) getValue();
30.       StringBuffer s = new StringBuffer();
31.       for (int i = 0; i < 3; i++)
32.       {
33.          if (values.length > i) s.append(values[i]);
34.          if (values.length > i + 1) s.append(", ");
35.       }
36.       if (values.length > 3) s.append("...");
37.
38.       g2.setColor(Color.white);
39.       g2.fill(box);
40.       g2.setColor(Color.black);
41.       FontRenderContext context = g2.getFontRenderContext();
42.       Rectangle2D stringBounds = g2.getFont().getStringBounds(
43.          s.toString(), context);
44.       double w = stringBounds.getWidth();
45.       double x = box.x;
46.       if (w < box.width) x += (box.width - w) / 2;
47.       double ascent = -stringBounds.getY();
48.       double y = box.y
49.          + (box.height - stringBounds.getHeight()) / 2 + ascent;
50.       g2.drawString(s.toString(), (float)x, (float)y);
51.    }
52.
53.    public String getAsText()
54.    {
55.       return null;
56.    }
57. }
Example 8-14 DoubleArrayEditorPanel.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.text.*;
  4. import java.lang.reflect.*;
  5. import java.beans.*;
  6. import javax.swing.*;
  7. import javax.swing.event.*;
  8.
  9. /**
 10.    The panel inside the DoubleArrayEditor. It contains
 11.    a list of the array values, together with buttons to
 12.    resize the array and change the currently selected list value.
 13. */
 14. public class DoubleArrayEditorPanel extends JPanel
 15. {
 16.    public DoubleArrayEditorPanel(PropertyEditorSupport ed)
 17.    {
 18.       editor = ed;
 19.       setArray((double[])ed.getValue());
 20.
 21.       setLayout(new GridBagLayout());
 22.       GridBagConstraints gbc = new GridBagConstraints();
 23.
 24.       gbc.weightx = 100;
 25.       gbc.weighty = 0;
 26.       gbc.fill = GridBagConstraints.HORIZONTAL;
 27.
 28.       add(sizeField, gbc, 0, 0, 1, 1);
 29.       add(valueField, gbc, 0, 1, 1, 1);
 30.
 31.       gbc.fill = GridBagConstraints.NONE;
 32.
 33.       add(sizeButton, gbc, 1, 0, 1, 1);
 34.       add(valueButton, gbc, 1, 1, 1, 1);
 35.
 36.       sizeButton.addActionListener(new
 37.          ActionListener()
 38.          {
 39.             public void actionPerformed(ActionEvent event)
 40.             {
 41.                changeSize();
 42.             }
 43.          });
 44.
 45.       valueButton.addActionListener(new
 46.          ActionListener()
 47.          {
 48.             public void actionPerformed(ActionEvent event)
 49.             {
 50.                changeValue();
 51.             }
 52.          });
 53.
 54.       gbc.weighty = 100;
 55.       gbc.fill = GridBagConstraints.BOTH;
 56.
 57.       add(new JScrollPane(elementList), gbc, 0, 2, 2, 1);
 58.
 59.       elementList.setSelectionMode(
 60.          ListSelectionModel.SINGLE_SELECTION);
 61.
 62.       elementList.addListSelectionListener(new
 63.          ListSelectionListener()
 64.          {
 65.             public void valueChanged(ListSelectionEvent event)
 66.             {
 67.                int i = elementList.getSelectedIndex();
 68.                if (i < 0) return;
 69.                valueField.setText("" + array[i]);
 70.             }
 71.          });
 72.
 73.       elementList.setModel(model);
 74.       elementList.setSelectedIndex(0);
 75.    }
 76.
 77.    /**
 78.       A convenience method to add a component to given grid bag
 79.       layout locations.
 80.       @param c the component to add
 81.       @param gbc the grid bag constraints to use
 82.       @param x the x grid position
 83.       @param y the y grid position
 84.       @param w the grid width
 85.       @param h the grid height
 86.    */
 87.    public void add(Component c, GridBagConstraints gbc,
 88.       int x, int y, int w, int h)
 89.    {
 90.       gbc.gridx = x;
 91.       gbc.gridy = y;
 92.       gbc.gridwidth = w;
 93.       gbc.gridheight = h;
 94.       add(c, gbc);
 95.    }
 96.
 97.    /**
 98.       This method is called when the user wants to change
 99.       the size of the array.
100.    */
101.    public void changeSize()
102.    {
103.       fmt.setParseIntegerOnly(true);
104.       int s = 0;
105.       try
106.       {
107.          s = fmt.parse(sizeField.getText()).intValue();
108.          if (s < 0)
109.             throw new ParseException("Out of bounds", 0);
110.       }
111.       catch(ParseException e)
112.       {
113.          JOptionPane.showMessageDialog(this, "" + e,
114.             "Input Error", JOptionPane.WARNING_MESSAGE);
115.          sizeField.requestFocus();
116.          return;
117.       }
118.       if (s == array.length) return;
119.       setArray((double[])arrayGrow(array, s));
120.       editor.setValue(array);
121.       editor.firePropertyChange();
122.    }
123.
124.    /**
125.       This method is called when the user wants to change
126.       the currently selected array value.
127.    */
128.    public void changeValue()
129.    {
130.       double v = 0;
131.       fmt.setParseIntegerOnly(false);
132.       try
133.       {
134.          v = fmt.parse(valueField.getText()).doubleValue();
135.       }
136.       catch(ParseException e)
137.       {
138.          JOptionPane.showMessageDialog(this, "" + e,
139.             "Input Error", JOptionPane.WARNING_MESSAGE);
140.          valueField.requestFocus();
141.          return;
142.       }
143.       int currentIndex = elementList.getSelectedIndex();
144.       setArray(currentIndex, v);
145.       editor.firePropertyChange();
146.    }
147.
148.    /**
149.       Sets the indexed array property.
150.       @param v the array to edit
151.    */
152.    public void setArray(double[] v)
153.    {
154.       if (v == null) array = new double[0];
155.       else array = v;
156.       model.setArray(array);
157.       sizeField.setText("" + array.length);
158.       if (array.length > 0)
159.       {
160.          valueField.setText("" + array[0]);
161.          elementList.setSelectedIndex(0);
162.       }
163.       else
164.          valueField.setText("");
165.    }
166.
167.    /**
168.       Gets the indexed array property.
169.       @return the array being edited
170.    */
171.    public double[] getArray()
172.    {
173.       return (double[])array.clone();
174.    }
175.
176.    /**
177.       Sets the indexed array property.
178.       @param i the index whose value to set
179.       @param value the new value for the given index
180.    */
181.    public void setArray(int i, double value)
182.    {
183.       if (0 <= i && i < array.length)
184.       {
185.          model.setValue(i, value);
186.          elementList.setSelectedIndex(i);
187.          valueField.setText("" + value);
188.       }
189.    }
190.
191.    /**
192.       Gets the indexed array property.
193.       @param i the index whose value to get
194.       @return the value at the given index
195.    */
196.    public double getArray(int i)
197.    {
198.       if (0 <= i && i < array.length) return array[i];
199.       return 0;
200.    }
201.
202.    /**
203.       Resizes an array
204.       @param a the array to grow
205.       @param newLength the new length
206.       @return an array with the given length and the same
207.       elements as a in the common positions
208.    */
209.    private static Object arrayGrow(Object a, int newLength)
210.    {
211.       Class cl = a.getClass();
212.       if (!cl.isArray()) return null;
213.       Class componentType = a.getClass().getComponentType();
214.       int length = Array.getLength(a);
215.
216.       Object newArray = Array.newInstance(componentType,
217.          newLength);
218.       System.arraycopy(a, 0, newArray, 0,
219.          Math.min(length, newLength));
220.       return newArray;
221.    }
222.
223.    private PropertyEditorSupport editor;
224.    private double[] array;
225.    private NumberFormat fmt = NumberFormat.getNumberInstance();
226.    private JTextField sizeField = new JTextField(4);
227.    private JTextField valueField = new JTextField(12);
228.    private JButton sizeButton = new JButton("Resize");
229.    private JButton valueButton = new JButton("Change");
230.    private JList elementList = new JList();
231.    private DoubleArrayListModel model = new DoubleArrayListModel();
232. }
233.
234. /**
235.    The list model for the element list in the editor.
236. */
237. class DoubleArrayListModel extends AbstractListModel
238. {
239.    public int getSize()
240.    {
241.       return array.length;
242.    }
243.
244.    public Object getElementAt(int i)
245.    {
246.       return "[" + i + "] " + array[i];
247.    }
248.
249.    /**
250.       Sets a new array to be displayed in the list.
251.       @param a the new array
252.    */
253.    public void setArray(double[] a)
254.    {
255.       int oldLength = array == null ? 0 : array.length;
256.       array = a;
257.       int newLength = array == null ? 0 : array.length;
258.       if (oldLength > 0) fireIntervalRemoved(this, 0, oldLength);
259.       if (newLength > 0) fireIntervalAdded(this, 0, newLength);
260.    }
261.
262.    /**
263.       Changes a value in the array to be displayed in the list.
264.       @param i the index whose value to change
265.       @param value the new value for the given index
266.    */
267.    public void setValue(int i, double value)
268.    {
269.       array[i] = value;
270.       fireContentsChanged(this, i, i);
271.    }
272.
273.    private double[] array;
274. }
Summing Up

For every property editor you write, you have to choose one of three ways to display and edit the property value:

You saw examples of all three cases in the chart bean.

Finally, some property editors might want to support a method called getJavaInitializationString. With this method, you can give the builder tool the Java programming language code that sets a property to allow automatic code generation. We did not show you an example for this method.

java.beans.PropertyEditorSupport

graphics/api.gif
 

Going Beyond Naming Patterns

You have already seen that if you use the standard naming conventions for the members of your bean, then a builder tool can use reflection to determine the properties, events, and methods of your bean. This process makes it simple to get started with bean programming but is rather limiting in the end. As your beans become in any way complex, there will be features of your bean that naming patterns and reflection will simply not reveal. (Not to mention that using English naming patterns as the basis for all GUI builders in all languages for all times seems to be rather against the spirit of providing support for your international customers.) Moreover, as we already mentioned, there may well be get/set pairs that you do not want to expose as bean properties.

Luckily, the JavaBeans specification allows a far more flexible and powerful mechanism for storing information about your bean for use by a builder. As with many features of beans, the mechanism is simple in theory but can be tedious to carry out in practice. The idea is that you again use an object that implements the BeanInfo interface. (Recall that we used one feature of the BeanInfo class when we supplied property editors for the chart bean class.)

When you implement this interface to describe your bean, a builder tool will look to the methods from the BeanInfo interface to tell it (potentially quite detailed) information about the properties, events, and methods your bean supports. The BeanInfo is supposed to free you from the tyranny of naming patterns. Somewhat ironically, the JavaBeans specification does require that you use a naming pattern to associate a BeanInfo object to the bean. You specify the name of the bean info class by adding BeanInfo to the name of the bean. For example, the bean info class associated to the class ChartBean must be named ChartBeanBeanInfo. The bean info class must be part of the same package as the bean itself.

NOTE

graphics/note.gif
 

Any descriptions you supply in the bean info associated to your bean override any information that the builder might obtain by reflecting on the member names. Moreover, if you supply information about a feature set (such as the properties that your bean supports), you must then provide information about all the properties in the associated bean info.

As you already saw, you won't normally write from scratch a class that implements the BeanInfo interface. Instead, you will probably turn again to the SimpleBeanInfo convenience class that has empty implementations (returning null) for all the methods in the BeanInfo interface. This practice is certainly convenient—just override the methods you really want to change. Moreover, this convenience class includes a useful method called loadImage that you can use to load an image (such as an icon—see below) for your bean. We use the SimpleBeanInfo class for all our examples of BeanInfo classes. For example, our ChartBeanBeanInfo class starts out:

public class ChartBeanBeanInfo extends SimpleBeanInfo

NOTE

graphics/note.gif
 

That the methods in the SimpleBeanInfo class return null is actually quite important. This is exactly how the builder tool knows how to use naming patterns to find out the members of that feature set. A non-null return value turns off the reflective search.

For a taste of what you can do with the bean info mechanism, let's start with an easy-to-use, but most useful, method in the BeanInfo interface: the getIcon method that lets you give your bean a custom icon. This is useful since builder tools will usually want to have an icon for the bean for some sort of palette. Builder environments show the icons next to the bean name in the bean toolbox. Actually, you can specify separate icon bitmaps. The BeanInfo interface has four constants that cover the standard sizes.

ICON_COLOR_16x16
ICON_COLOR_32x32
ICON_MONO_16x16
ICON_MONO_32x32

Here is an example of how you might use the loadImage convenience method in the SimpleBeanInfo class to add an icon to a class:

public Image getIcon(int iconType)
{
   String name = "";
   if (iconType == BeanInfo.ICON_COLOR_16x16)
      name = "COLOR_16x16";
   else if (iconType == BeanInfo.ICON_COLOR_32x32)
      name = "COLOR_32x32";
   else if (iconType == BeanInfo.ICON_MONO_16x16)
      name = "MONO_16x16";
   else if (iconType == BeanInfo.ICON_MONO_32x32)
      name = "MONO_32x32";
   else return null;
   return loadImage("ChartBean_" + name + ".gif");
}

where we have cleverly named the image files to be

ChartBean_COLOR_16x16.gif
ChartBean_COLOR_32x32.gif

and so on.

FeatureDescriptor Objects

The key to using any of the more advanced features of the BeanInfo class is the FeatureDescriptor class and its various subclasses. As its name suggests, a FeatureDescriptor object provides information about a feature. Examples of features are properties, events, methods, and so on. More precisely, the FeatureDescriptor class is the superclass for all descriptors, and it factors out the common operations that you need to deal with when trying to describe any feature. For example, the name of the feature is obtained through the getName method. Since this method is in the superclass, it works for all feature descriptors, no matter what they describe. Here are the subclasses of the FeatureDescriptor class:

These classes all work basically the same. You create a descriptor object for each member you are trying to describe, and you collect all descriptors of a feature set in an array and return it as the return value of one of the BeanInfo methods.

For example, to turn off reflection for event sets, you'll return an array of EventSetDescriptor objects in your bean info class.

class MyBeanBeanInfo extends SimpleBeanInfo
{  public EventSetDescriptor[] getEventSetDescriptors()

   {  . . .

   }

   . . .
}

Next, you'll construct all the various EventSetDescriptor objects that will go into this array. Generally, all the constructors for the various kinds of FeatureDescriptor objects work in the same way. In particular, for events, the most common constructor takes:

Other constructors let you specify the methods of the bean that should be used to add and remove EventListener objects.

A good example of all this can be found in the BeanInfo class associated with the ExplicitButtonBean that ships with the BDK. Let's analyze the code that creates the needed event descriptors for this bean. The ExplicitButtonBean fires two events: when the button is pushed and when the state of the button has changed. Here's how you build these two EventSetDescriptor objects associated to these two events:

EventSetDescriptor push = new EventSetDescriptor(beanClass,
   "actionPerformed",
   java.awt.event.ActionListener.class,
   "actionPerformed");

EventSetDescriptor changed = new EventSetDescriptor(beanClass,
   "propertyChange",
   java.beans.PropertyChangeListener.class,
   "propertyChange");

The next step is to set the various display names for the events for the EventSetDescriptor. In the code for the ExplicitButton in the BeanInfo class, this is done by

push.setDisplayName("button push");
changed.setDisplayName("bound property change");

Actually, it is a little messier to code the creation of the needed EventSetDescriptor objects than the above fragments indicate because all constructors for feature descriptor objects can throw an IntrospectionException. So, you actually have to build the array of descriptors in a try/catch block, as the following code indicates.

public EventSetDescriptor[] getEventSetDescriptors()
{
   try
   {
      EventSetDescriptor push = new
         EventSetDescriptor(beanClass,
            "actionPerformed",
            java.awt.event.ActionListener.class,
            "actionPerformed");

      EventSetDescriptor changed = new
         EventSetDescriptor(beanClass,
            "propertyChange",
            java.beans.PropertyChangeListener.class,
            "propertyChange");

      push.setDisplayName("button push");
      changed.setDisplayName("bound property change");
      return new EventSetDescriptor[] { push, changed };
   }
   catch (IntrospectionException e)
   {
      throw new RuntimeException(e.toString());
   }
}

This particular event set descriptor is needed because the event descriptors differ from the standard naming pattern. Specifically, there are two differences:

To summarize: When any feature of your bean differs from the standard naming pattern, you must do the following:

java.beans.BeanInfo

graphics/api.gif
 

java.beans.SimpleBeanInfo

graphics/api.gif
 

java.beans.FeatureDescriptor

graphics/api.gif
 

java.beans.EventSetDescriptor

graphics/api.gif
 

java.beans.PropertyDescriptor

graphics/api.gif
 

java.beans.IndexedPropertyDescriptor

graphics/api.gif
 

java.beans.MethodDescriptor

graphics/api.gif
 

java.beans.ParameterDescriptor

graphics/api.gif
 

Customizers

A property editor, no matter how sophisticated, is responsible for allowing the user to set one property at a time. Especially if certain properties of a bean relate to each other, it may be more user friendly to give users a way to edit multiple properties at the same time. To enable this feature, you supply a customizer instead of (or in addition to) multiple property editors.

In the example program for this section, we develop a customizer for the chart bean. The customizer lets you set several properties of the chart bean at once, and it lets you specify a file from which to read the data points for the chart. Figure 8-22 shows you one pane of the customizer for the ChartBean.

Figure 8-22. The customizer for the ChartBean

graphics/08fig22.gif
 

To add a customizer to your bean, you must supply a BeanInfo class and override the getBeanDescriptor method, as shown in the following example.

public BeanDescriptor getBeanDescriptor()
{
   return new BeanDescriptor(ChartBean.class,
      ChartBeanCustomizer.class);
}

The general procedure for your customizers follows the same model.

  1. Override the getBeanDescriptor method by returning a new BeanDescriptor object for your bean.

  2. Specify the customizer class as the second parameter of the constructor for the BeanDescriptor object.

Note that you need not follow any naming pattern for the customizer class. The builder can locate it by

  1. Finding the associated BeanInfo class;

  2. Invoking its getBeanDescriptor method;

  3. Calling the getCustomizerClass method.

    (Nevertheless, it is customary to name the customizer as BeanNameCustomizer.)

Example 8-15 has the code for the ChartBeanBeanInfo class that references the ChartBeanCustomizer. You will see in the next section how that customizer is implemented.

Example 8-15 ChartBeanBeanInfo.java
 1. import java.awt.*;
 2. import java.beans.*;
 3.
 4. /**
 5.    The bean info for the chart bean, specifying the
 6.    icons and the customizer.
 7. */
 8. public class ChartBeanBeanInfo extends SimpleBeanInfo
 9. {
10.    public BeanDescriptor getBeanDescriptor()
11.    {
12.       return new BeanDescriptor(ChartBean.class,
13.          ChartBeanCustomizer.class);
14.    }
15.
16.    public Image getIcon(int iconType)
17.    {
18.       String name = "";
19.       if (iconType == BeanInfo.ICON_COLOR_16x16)
20.          name = "COLOR_16x16";
21.       else if (iconType == BeanInfo.ICON_COLOR_32x32)
22.          name = "COLOR_32x32";
23.       else if (iconType == BeanInfo.ICON_MONO_16x16)
24.          name = "MONO_16x16";
25.       else if (iconType == BeanInfo.ICON_MONO_32x32)
26.          name = "MONO_32x32";
27.       else return null;
28.       return loadImage("ChartBean_" + name + ".gif");
29.    }
30. }

java.beans.BeanInfo

graphics/api.gif
 

java.beans.BeanDescriptor

graphics/api.gif
 

Writing a Customizer Class

Any customizer class you write must implement the Customizer interface. There are only three methods in this interface:

It is a good idea to update the visual appearance of the target bean by broadcasting a PropertyChangeEvent whenever the user changes any of the property values, not just when the user is at the end of the customization process.

Unlike property editors, customizers are not automatically displayed. In the BeanBox, you must select Edit -> Customize to pop up the customizer of a bean. At that point, the BeanBox will call the setObject method of the customizer that takes the bean being customized as a parameter. Notice that your customizer is thus created before it is actually linked to an instance of your bean. Therefore, you cannot assume any information about the state of a bean in the customizer, and you must provide a default constructor, that is, one without arguments.

There are three parts to writing a customizer class:

  1. Building the visual interface;

  2. Initializing the customizer in the setObject method;

  3. Updating the bean by firing property change events when the user changes properties in the interface.

By definition, a customizer class is visual. It must, therefore, extend Component or a subclass of Component, such as JPanel. Since customizers typically present the user with many options, it is often handy to use the tabbed pane interface. We use this approach and have the customizer extend the JTabbedPane interface.

CAUTION

graphics/caution.gif
 

We had quite a bit of grief with placing a JTabbedPane inside the customizer dialog of the BeanBox. The BeanBox uses the old AWT components. Somehow the events became entangled between the AWT and Swing components and clicking on the tabs did not flip the panes. By trial and error, we found that trapping the tab clicks and calling validate fixed this problem. Presumably, in the long run, this issue will go away when all bean environments use Swing.

The customizer gathers the information in three panes:

Of course, developing this kind of user interface can be tedious to code—our example devotes over 100 lines just to set it up in the constructor. However, this task requires only the usual Swing programming skills, and we won't dwell on the details here.

There is one trick that is worth keeping in mind. You often need to edit property values in a customizer. Rather than implementing a new interface for setting the property value of a particular class, you can simply locate an existing property editor and add it to your user interface! For example, in our ChartBean customizer, we need to set the graph color. Since we know that the BeanBox has a perfectly good property editor for colors, we locate it as follows:

PropertyEditor colorEditor
   = PropertEditorManager.findEditor(Color.Class);

We then call getCustomEditor to get the component that contains the user interface for setting the colors.

Component colorEditorComponent = colorEditor.getCustomEditor();
// now add this component to the UI

Once we have all components laid out, we initialize their values in the setObject method. The setObject method is called when the customizer is displayed. Its parameter is the bean that is being customized. To proceed, we store that bean reference—we'll need it later to notify the bean of property changes. Then, we initialize each user interface component. Here is a part of the setObject method of the chart bean customizer that does this initialization.

public void setObject(Object obj)
{
   bean = (ChartBean)obj;
   titleField.setText(bean.getTitle());
   colorEditor.setValue(bean.getGraphColor());
   . . .
}

Finally, we hook up event handlers to track the user's activities. Whenever the user changes the value of a component, the component fires an event that our customizer must handle. The event handler must update the value of the property in the bean and must also fire a PropertyChangeEvent so that other listeners (such as the property inspector) can be updated. Let us follow that process with a couple of user interface elements in the chart bean customizer.

When the user types a new title, we want to update the title property. We attach a DocumentListener to the text field into which the user types the title.

titleField.getDocument().addDocumentListener(new
   DocumentListener()
   {
      public void changedUpdate(DocumentEvent event)
      {
         setTitle(titleField.getText());
      }
      public void insertUpdate(DocumentEvent event)
      {
         setTitle(titleField.getText());
      }
      public void removeUpdate(DocumentEvent event)
      {
         setTitle(titleField.getText());
      }
   });

The three listener methods call the setTitle method of the customizer. That method calls the bean to update the property value and then fires a property change event. (This update is necessary only for properties that are not bound.) Here is the code for the setTitle method.

public void setTitle(String newValue)
{
   if (bean == null) return;
   String oldValue = bean.getTitle();
   bean.setTitle(newValue);
   firePropertyChange("title", oldValue, newValue);
}

When the color value changes in the color property editor, we want to update the graph color of the bean. We track the color changes by attaching a listener to the property editor. Perhaps confusingly, that editor also sends out property change events.

colorEditor.addPropertyChangeListener(new
   PropertyChangeListener()
   {
      public void propertyChange(PropertyChangeEvent
         event)
      {
         setGraphColor((Color)colorEditor.getValue());
      }
   });

Whenever the color value of the color property editor changes, we call the setGraphColor method of the customizer. That method updates the graphColor property of the bean and fires a different property change event that is associated with the graphColor property.

public void setGraphColor(Color newValue)
{
   if (bean == null) return;
   Color oldValue = bean.getGraphColor();
   bean.setGraphColor(newValue);
   firePropertyChange("graphColor", oldValue, newValue);
}

Example 8-16 provides the full code of the chart bean customizer.

This particular customizer just sets properties of the bean. In general, customizers can call any methods of the bean, whether or not they are property setters. That is, customizers are more general than property editors. (Some beans may have features that are not exposed as properties and that can be edited only through the customizer.)

Example 8-16 ChartBeanCustomizer.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.beans.*;
  4. import java.io.*;
  5. import java.text.*;
  6. import java.util.*;
  7. import javax.swing.*;
  8. import javax.swing.event.*;
  9.
 10. /**
 11.    A customizer for the chart bean that allows the user to
 12.    edit all chart properties in a single tabbed dialog.
 13. */
 14. public class ChartBeanCustomizer extends JTabbedPane
 15.    implements Customizer
 16. {
 17.    public ChartBeanCustomizer()
 18.    {
 19.       data = new JTextArea();
 20.       JPanel dataPane = new JPanel();
 21.       dataPane.setLayout(new BorderLayout());
 22.       dataPane.add(new JScrollPane(data), BorderLayout.CENTER);
 23.       JButton dataButton = new JButton("Set data");
 24.       dataButton.addActionListener(new
 25.          ActionListener()
 26.          {
 27.             public void actionPerformed(ActionEvent event)
 28.             {
 29.                setData(data.getText());
 30.             }
 31.          });
 32.       JPanel p = new JPanel();
 33.       p.add(dataButton);
 34.       dataPane.add(p, BorderLayout.SOUTH);
 35.
 36.       JPanel colorPane = new JPanel();
 37.       colorPane.setLayout(new BorderLayout());
 38.
 39.       normal = new JCheckBox("Normal", true);
 40.       inverse = new JCheckBox("Inverse", false);
 41.       p = new JPanel();
 42.       p.add(normal);
 43.       p.add(inverse);
 44.       ButtonGroup g = new ButtonGroup();
 45.       g.add(normal);
 46.       g.add(inverse);
 47.       normal.addActionListener(new
 48.          ActionListener()
 49.          {
 50.             public void actionPerformed(ActionEvent event)
 51.             {
 52.                setInverse(false);
 53.             }
 54.          });
 55.
 56.       inverse.addActionListener(
 57.          new ActionListener()
 58.          {
 59.             public void actionPerformed(ActionEvent event)
 60.             {
 61.                setInverse(true);
 62.             }
 63.          });
 64.
 65.       colorEditor
 66.          = PropertyEditorManager.findEditor(Color.class);
 67.       colorEditor.addPropertyChangeListener(
 68.          new PropertyChangeListener()
 69.          {
 70.             public void propertyChange(PropertyChangeEvent
 71.                evt)
 72.             {
 73.                setGraphColor((Color)colorEditor.getValue());
 74.             }
 75.          });
 76.
 77.       colorPane.add(p, BorderLayout.NORTH);
 78.       colorPane.add(colorEditor.getCustomEditor(),
 79.          BorderLayout.CENTER);
 80.
 81.       JPanel titlePane = new JPanel();
 82.       titlePane.setLayout(new BorderLayout());
 83.
 84.       g = new ButtonGroup();
 85.       position = new JCheckBox[3];
 86.       position[0] = new JCheckBox("Left", false);
 87.       position[1] = new JCheckBox("Center", true);
 88.       position[2] = new JCheckBox("Right", false);
 89.
 90.       p = new JPanel();
 91.       for (int i = 0; i < position.length; i++)
 92.       {
 93.          final int value = i;
 94.          p.add(position[i]);
 95.          g.add(position[i]);
 96.          position[i].addActionListener(new
 97.             ActionListener()
 98.             {
 99.                public void actionPerformed(ActionEvent event)
100.                {
101.                   setTitlePosition(value);
102.                }
103.             });
104.       }
105.
106.       titleField = new JTextField();
107.       titleField.getDocument().addDocumentListener(
108.          new DocumentListener()
109.          {
110.             public void changedUpdate(DocumentEvent evt)
111.             {
112.                setTitle(titleField.getText());
113.             }
114.             public void insertUpdate(DocumentEvent evt)
115.             {
116.                setTitle(titleField.getText());
117.             }
118.             public void removeUpdate(DocumentEvent evt)
119.             {
120.                setTitle(titleField.getText());
121.             }
122.          });
123.
124.       titlePane.add(titleField, BorderLayout.NORTH);
125.       titlePane.add(p, BorderLayout.SOUTH);
126.       addTab("Color", colorPane);
127.       addTab("Title", titlePane);
128.       addTab("Data", dataPane);
129.
130.       // workaround for a JTabbedPane bug in JDK 1.2
131.       addChangeListener(new
132.          ChangeListener()
133.          {
134.             public void stateChanged(ChangeEvent event)
135.             {
136.                validate();
137.             }
138.          });
139.    }
140.
141.    /**
142.       Sets the data to be shown in the chart.
143.       @param s a string containing the numbers to be displayed,
144.       separated by white space
145.    */
146.    public void setData(String s)
147.    {
148.       StringTokenizer tokenizer = new StringTokenizer(s);
149.
150.       int i = 0;
151.       double[] values = new double[tokenizer.countTokens()];
152.       while (tokenizer.hasMoreTokens())
153.       {
154.          String token = tokenizer.nextToken();
155.          try
156.          {
157.             values[i] = Double.parseDouble(token);
158.             i++;
159.          }
160.          catch (NumberFormatException exception)
161.          {
162.          }
163.       }
164.       setValues(values);
165.    }
166.
167.    /**
168.       Sets the title of the chart.
169.       @param newValue the new title
170.    */
171.    public void setTitle(String newValue)
172.    {
173.       if (bean == null) return;
174.       String oldValue = bean.getTitle();
175.       bean.setTitle(newValue);
176.       firePropertyChange("title", oldValue, newValue);
177.    }
178.
179.    /**
180.       Sets the title position of the chart.
181.       @param i the new title position (ChartBean.LEFT,
182.       ChartBean.CENTER, or ChartBean.RIGHT)
183.    */
184.    public void setTitlePosition(int i)
185.    {
186.       if (bean == null) return;
187.       Integer oldValue = new Integer(bean.getTitlePosition());
188.       Integer newValue = new Integer(i);
189.       bean.setTitlePosition(i);
190.       firePropertyChange("titlePosition", oldValue, newValue);
191.    }
192.
193.    /**
194.       Sets the inverse setting of the chart.
195.       @param b true if graph and background color are inverted
196.    */
197.    public void setInverse(boolean b)
198.    {
199.       if (bean == null) return;
200.       Boolean oldValue = new Boolean(bean.isInverse());
201.       Boolean newValue = new Boolean(b);
202.       bean.setInverse(b);
203.       firePropertyChange("inverse", oldValue, newValue);
204.    }
205.
206.    /**
207.       Sets the values to be shown in the chart.
208.       @param newValue the new value array
209.    */
210.    public void setValues(double[] newValue)
211.    {
212.       if (bean == null) return;
213.       double[] oldValue = bean.getValues();
214.       bean.setValues(newValue);
215.       firePropertyChange("values", oldValue, newValue);
216.    }
217.
218.    /**
219.       Sets the color of the chart
220.       @param newValue the new color
221.    */
222.    public void setGraphColor(Color newValue)
223.    {
224.       if (bean == null) return;
225.       Color oldValue = bean.getGraphColor();
226.       bean.setGraphColor(newValue);
227.       firePropertyChange("graphColor", oldValue, newValue);
228.    }
229.
230.    public void setObject(Object obj)
231.    {
232.       bean = (ChartBean)obj;
233.
234.       data.setText("");
235.       double[] values = bean.getValues();
236.       for (int i = 0; i < values.length; i++)
237.          data.append(values[i] + "\n");
238.
239.       normal.setSelected(!bean.isInverse());
240.       inverse.setSelected(bean.isInverse());
241.
242.       titleField.setText(bean.getTitle());
243.
244.       for (int i = 0; i < position.length; i++)
245.          position[i].setSelected(i == bean.getTitlePosition());
246.
247.       colorEditor.setValue(bean.getGraphColor());
248.    }
249.
250.    public Dimension getPreferredSize()
251.    {
252.       return new Dimension(XPREFSIZE, YPREFSIZE);
253.    }
254.
255.    private static final int XPREFSIZE = 200;
256.    private static final int YPREFSIZE = 120;
257.    private ChartBean bean;
258.    private PropertyEditor colorEditor;
259.
260.    private JTextArea data;
261.    private JCheckBox normal;
262.    private JCheckBox inverse;
263.    private JCheckBox[] position;
264.    private JTextField titleField;
265. }
java.beans.Customizer

graphics/api.gif
 

The Bean Context

In this section, we show how you can write beans that take advantage of their environment. This is useful to implement beans that interact with other beans or with services that the bean context provides. In particular, you will see how to implement a bean that can change the value of an arbitrary integer property of another bean, and how a bean can use a bean context service.

CAUTION

graphics/caution.gif
 

Somewhat unhappily, the most commonly available builder environments on the market today (including Forte) do not implement bean contexts. The examples in this section work in the BeanBox, but they probably won't work at all in your favorite builder tool.

Advanced Uses of Introspection

From the point of view of the JavaBeans specification, introspection is simply the process by which a builder tool finds out which properties, methods, and events a bean supports. Introspection is carried out in two ways:

Normally, introspection is an activity that is reserved for bean environments. The bean environment uses introspection to learn about beans, but the beans themselves don't need to carry out introspection. However, there are some cases when one bean needs to use introspection to analyze other beans. A good example is when you want to tightly couple two beans on a form in a builder tool. Consider, for example, a spin bean, a small control element with two buttons, to increase or decrease a value (see Figure 8-23).

Figure 8-23. The spin bean

graphics/08fig23.gif
 

A spin bean by itself is not useful. It needs to be coupled with another bean. For example, a spin bean can be coupled to an integer text bean. Each time the user clicks on one of the buttons of the spin bean, the integer value is incremented or decremented. We will call the coupled bean the buddy of the spin bean. The buddy does not have to be an IntTextBean. It can be any other bean with an integer property.

You use the customizer of the spin bean to attach the buddy (see Figure 8-24).

Figure 8-24. The customizer of the SpinBean

graphics/08fig24.gif
 

Here is how you can try it out.

  1. Compile the SpinBean and IntTextBean and create the JAR files.

  2. Start the BeanBox.

  3. Load the SpinBean.jar and IntTextBean.jar file.

  4. Add the SpinBean and an IntTextBean on the form.

  5. Pop up the customizer of the spin bean by selecting it and selecting Edit -> Customize from the menu.

  6. Select the IntTextBean in the Buddy list.

  7. Watch how all the int properties in the Property list are automatically filled in (see Figure 8-24).

  8. Select value and click on Set Buddy.

  9. Click on Done.

  10. Then, click on + and - and watch the integer text field value increase and decrease (see Figure 8-25).

    Figure 8-25. The SpinBean coupled with an IntTextBean buddy

    graphics/08fig25.gif
     

It looks easy, but there were two challenges to implementing this customization.

We use introspection (that is, the reflection API) to solve both of these problems. To analyze the properties of a bean, first get the bean info by calling the static getBeanInfo method of the Introspector class.

BeanInfo info
   = Introspector.getBeanInfo(buddy.getClass());

Once we have the bean info, we can obtain an array of property descriptors:

PropertyDescriptor[] props = info.getPropertyDescriptors();

In the spin bean customizer, the next step is to loop through this array, picking out all properties of type int and adding their names to a list component.

for (int i = 0; i < props.length; i++)
{
   Class propertyType = props[i].getPropertyType();
   if (int.class.equals(propertyType))
   {
      String name = props[i].getName();
      propModel.addElement(name);
   }
}

This code shows how you can find out about the properties of a bean.

Next, we need to be able to get and set the property that the user selected. We obtain the get and set methods by calls to getReadMethod and getWriteMethod:

Method getMethod = prop.getReadMethod();
Method setMethod = prop.getWriteMethod();

(Why is it called getReadMethod? Probably because getGetMethod sounds too silly.)

Now, we invoke the methods to get a value, increment it, and set it. This process again uses the reflection API—see, for example, Chapter 5 of Volume 1. Note that we must use an Integer wrapper around the int value.

int value = ((Integer)getMethod.invoke(buddy,
   null)).intValue();
value += increment;
setMethod.invoke(buddy,
   new Object[] { new Integer(value) });

Could we have avoided reflection if we had demanded that the buddy have methods getValue and setValue? No. You can only call

int value = buddy.getValue();

when the compiler knows that buddy is an object of a type that has a getValue method. But buddy can be of any type—there is no type hierarchy for beans. Whenever one bean is coupled with another arbitrary bean, then you need to use introspection.

Finding Sibling Beans

In the preceding section, you saw how the spin bean buttons were able to change the value of the buddy component. However, there is another unrelated issue—how can the spin bean customizer present all possible buddies to the user?

It is a bit more difficult to enumerate all beans on a form than you might think. In the BeanBox, for example, you can't simply call

Component[] siblings = getParent().getComponents()

to get all the siblings of a bean. The reason you can't do this is that the BeanBox surrounds every bean by a panel within a panel. (We suspect that is done to detect mouse clicks that select the bean, and to draw the outline around a selected bean.) So, in the BeanBox, we'd have to write

Component[] siblings
   = getParent().getParent().getParent().getComponents()

However, there is no guarantee that this solution would work in another builder environment—since those environments might be smart enough not to need all these extra panels.

In the Java 2 platform, we can solve this problem. The JavaBeans architecture now supports the concept of a bean context. Bean contexts express the logical containment between beans and bean containers, which, as you just saw, can be quite different from the physical containment.

A bean context can hold beans, services, and other bean contexts, just like an AWT container can hold components and other containers (see Figure 8-26).

Figure 8-26. Bean Contexts

graphics/08fig26.gif
 

Currently, nested bean contexts aren't common. At best, you can expect that your beans live in a single bean context, the builder environment. For example, the BeanBox in BDK 1.1 is a bean context. The BeanBox provides a message tracing service that beans can use to display logging messages. Other bean contexts may provide different services. In the next section, we show you how your beans can use the message tracing service.

To communicate with its surrounding bean context, a bean can implement the BeanContextChild interface. That interface has six methods:

void setBeanContext(BeanContext bc)
BeanContext getBeanContext()
void addPropertyChangeListener(String name,
   PropertyChangeListener listener)
void removePropertyChangeListener(String name,
   PropertyChangeListener listener)
void addVetoableChangeListener(String name,
   VetoableChangeListener listener)
void removeVetoableChangeListener(String name,
   VetoableChangeListener listener)

A bean context calls the setBeanContext method when it begins managing your bean. You can hold on to the BeanContext parameter value and use it whenever you need to access the ambient bean context.

Since it is tedious to implement the change listeners, a convenience class BeanContextChildSupport implements these methods for you. However, there is a technical issue if you want to use this convenience class. Since your bean can't simultaneously extend a component class and the BeanContextChildSupport class, you use a proxy mechanism. Follow these steps:

  1. Implement the BeanContextProxy interface.

  2. Construct an instance variable of type BeanContextChildSupport.

    private BeanContextChildSupport childSupport
       = new BeanContextChildSupport();
    
  3. Return that instance variable in the getBeanContextProxy method of the BeanContextProxy interface.

    public BeanContextChild getBeanContextProxy()
    {
      return childSupport;
    }
    

    The bean context calls this method to retrieve the proxy object. Then, it invokes the BeanContextChild methods on the returned object rather than on the bean itself.

  4. Call the getBeanContext method of the childSupport object whenever you want to know the current bean context.

    BeanContext context = childSupport.getBeanContext();
    

Figure 8-27 shows the relationships between these classes.

Figure 8-27. Relationships between the bean context classes

graphics/08fig27.gif
 

Once you have the bean context, you can enumerate all beans that it contains. The BeanContext class implements the Collection interface. Therefore, you can simply enumerate the beans as follows:

Iterator iter = beanContext.iterator();
while (iter.hasNext())
{
   Object buddy = iter.next();
   do something with buddy
}

From a user interface perspective, our approach—to list the types of the potential buddies—is still not satisfactory. If there is more than one sibling of the same class in the form, then the user cannot tell them apart. It would be nice if we could physically move the spin bean next to its buddy or draw a box around the selected buddy, but the BeanContext does not expose position information. (It is useless to ask the buddy about its location. It only knows its location with respect to its enclosing panel.) Perhaps a future version of the JavaBeans specification will allow such manipulations.

Using Bean Context Services

In this section, we want to show you how your beans can access services that a bean context provides. You have to know the class that provides the service that you want. For example, the message tracer service that the BeanBox provides is implemented by the class sunw.demo.methodtracer.MethodTracer. First, you need to make sure that the bean context implements the BeanContextServices interface—not all bean contexts do.

if (beanContext implements BeanContextServices)
{
   BeanContextServices services
     = (BeanContextServices)beanContext;
   . . .
}

Then, you ask the bean context if it supports the desired service.

tracerClass = Class.forName
   ("sunw.demo.methodtracer.MethodTracer");
if (services.hasService(tracerClass))
{
   . . .
}

If you run this bean in an environment other than the BeanBox, the hasService call may simply return false.

Finally, you need to get the object that carries out the service. You call the getService method with five parameters:

Here is a typical call.

BeanContextServiceRevokedListener revokedListener =
   new BeanContextServiceRevokedListener()
   {
      public void serviceRevoked
         (BeanContextServiceRevokedEvent event)
      {
         tracer = null;
      }
   };
tracer = services.getService(childSupport, this, tracerClass,
   null, revokedListener);

Note that you typically do not have the service class available when you compile your program. For example, the class file for the MethodTracer class is not part of the standard runtime library, and the compiler will not find it even if you try to import the sunw.demo.methodtracer package.

For that reason, we use reflection to call service methods. The following statements call the logText method of the MethodTracer class to display a message in the method tracer window.

if (tracer != null)
{
   String text = "spin: value=" + value
      + " increment=" + increment;
   Method logText = tracerClass.getMethod("logText",
      new Class[] { String.class });
   logText.invoke(tracer, new Object[] { text });
}

Of course, we don't call the method if the bean context doesn't support the service. If it does, we use the invoke method to call it through the reflection mechanism.

When you try out this example, watch the Message Tracer window. It contains a message for each click on one of the spin buttons (see Figure 8-28).

Figure 8-28. The Message Tracer window

graphics/08fig28.gif
 

Examples 8-17 through 8-19 contain the full code for the SpinBean, including the needed bean info class to hook in the customizer.

Example 8-17 SpinBean.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.beans.*;
  4. import java.beans.beancontext.*;
  5. import java.lang.reflect.*;
  6. import java.io.*;
  7. import java.util.*;
  8. import javax.swing.*;
  9.
 10. /**
 11.    A bean with + and - buttons that can increment or decrement
 12.    the value of a buddy bean.
 13. */
 14. public class SpinBean extends JPanel
 15.    implements BeanContextProxy
 16. {
 17.    public SpinBean()
 18.    {
 19.       setLayout(new GridLayout(2, 1));
 20.       JButton plusButton = new JButton("+");
 21.       JButton minusButton = new JButton("-");
 22.       add(plusButton);
 23.       add(minusButton);
 24.       plusButton.addActionListener(new
 25.          ActionListener()
 26.          {  public void actionPerformed(ActionEvent evt)
 27.             {
 28.                spin(1);
 29.             }
 30.          });
 31.       minusButton.addActionListener(new
 32.          ActionListener()
 33.          {  public void actionPerformed(ActionEvent evt)
 34.             {
 35.                spin(-1);
 36.             }
 37.          });
 38.
 39.       childSupport = new
 40.          BeanContextChildSupport()
 41.          {
 42.             public void setBeanContext(BeanContext context)
 43.                throws PropertyVetoException
 44.             {
 45.                super.setBeanContext(context);
 46.                setTracer(context);
 47.             }
 48.          };
 49.    }
 50.
 51.    public BeanContextChild getBeanContextProxy()
 52.    {
 53.       return childSupport;
 54.    }
 55.
 56.    /**
 57.       Sets the buddy of this spin bean.
 58.       @param b the buddy component
 59.       @param p the descriptor of the integer property to
 60.       increment or decrement
 61.    */
 62.    public void setBuddy(Component b, PropertyDescriptor p)
 63.    {
 64.       buddy = b;
 65.       prop = p;
 66.    }
 67.
 68.    /**
 69.       Increments or decrements the value of the buddy.
 70.       @param increment the amount by which to change the buddy's
 71.       value
 72.    */
 73.    public void spin(int increment)
 74.    {
 75.       if (buddy == null) return;
 76.       if (prop == null) return;
 77.       Method readMethod = prop.getReadMethod();
 78.       Method writeMethod = prop.getWriteMethod();
 79.       try
 80.       {  int value = ((Integer)readMethod.invoke(buddy,
 81.             null)).intValue();
 82.
 83.          if (tracer != null)
 84.          {  String text = "spin: value=" + value
 85.                + " increment=" + increment;
 86.             Method logText = tracerClass.getMethod("logText",
 87.                new Class[] { String.class });
 88.             logText.invoke(tracer, new Object[] { text });
 89.          }
 90.
 91.          value += increment;
 92.          writeMethod.invoke(buddy,
 93.             new Object[] { new Integer(value) });
 94.       }
 95.       catch(Exception e)
 96.       {
 97.       }
 98.    }
 99.
100.    /**
101.       Attempts to set the message tracing service.
102.       @param context the bean context that may provide the
103.       service.
104.    */
105.    public void setTracer(BeanContext context)
106.    {
107.       try
108.       {
109.          BeanContextServices services
110.            = (BeanContextServices)context;
111.          tracerClass = Class.forName
112.             ("sunw.demo.methodtracer.MethodTracer");
113.          if (services.hasService(tracerClass))
114.          {  BeanContextServiceRevokedListener revokedListener =
115.                new BeanContextServiceRevokedListener()
116.                {  public void serviceRevoked
117.                      (BeanContextServiceRevokedEvent event)
118.                   {  tracer = null;
119.                   }
120.                };
121.             tracer = services.getService(childSupport, this,
122.                tracerClass, null, revokedListener);
123.          }
124.       }
125.       catch (Exception exception)
126.       {
127.          tracer = null;
128.       }
129.    }
130.
131.    public Dimension getPreferredSize()
132.    {
133.       return new Dimension(MINSIZE, MINSIZE);
134.    }
135.
136.    private static final int MINSIZE = 20;
137.    private Component buddy;
138.    private PropertyDescriptor prop;
139.    private Object tracer;
140.    private Class tracerClass;
141.    private BeanContextChildSupport childSupport;
142. }
Example 8-18 SpinBeanCustomizer.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.beans.*;
  4. import java.beans.beancontext.*;
  5. import java.io.*;
  6. import java.text.*;
  7. import java.util.*;
  8. import javax.swing.*;
  9. import javax.swing.event.*;
 10.
 11. /**
 12.    A customizer for the spin bean to pick its buddy.
 13. */
 14. public class SpinBeanCustomizer extends JPanel
 15.    implements Customizer
 16. {
 17.    public SpinBeanCustomizer()
 18.    {
 19.       setLayout(new GridBagLayout());
 20.       GridBagConstraints gbc = new GridBagConstraints();
 21.       gbc.weightx = 0;
 22.       gbc.weighty = 100;
 23.       gbc.fill = GridBagConstraints.NONE;
 24.       gbc.anchor = GridBagConstraints.EAST;
 25.       add(new JLabel("Buddy"), gbc, 0, 0, 1, 1);
 26.       add(new JLabel("Property"), gbc, 0, 1, 1, 1);
 27.       gbc.weightx = 100;
 28.       gbc.anchor = GridBagConstraints.WEST;
 29.       gbc.fill = GridBagConstraints.BOTH;
 30.       buddyModel = new DefaultListModel();
 31.       propModel = new DefaultListModel();
 32.       buddyList = new JList(buddyModel);
 33.       propList = new JList(propModel);
 34.       add(new JScrollPane(buddyList), gbc, 1, 0, 1, 1);
 35.       add(new JScrollPane(propList), gbc, 1, 1, 1, 1);
 36.       JButton setButton = new JButton("Set Buddy");
 37.       JPanel p = new JPanel();
 38.       p.add(setButton);
 39.       add(p, gbc, 0, 2, 2, 1);
 40.
 41.       buddyList.addListSelectionListener(
 42.          new ListSelectionListener()
 43.          {
 44.             public void valueChanged(ListSelectionEvent event)
 45.             {
 46.                findBuddyMethods();
 47.             }
 48.          });
 49.
 50.       setButton.addActionListener(
 51.          new ActionListener()
 52.          {
 53.             public void actionPerformed(ActionEvent event)
 54.             {  int buddyIndex = buddyList.getSelectedIndex();
 55.                if (buddyIndex < 0) return;
 56.                int propIndex = propList.getSelectedIndex();
 57.                if (propIndex < 0) return;
 58.                bean.setBuddy(buddies[buddyIndex],
 59.                   props[propIndex]);
 60.             }
 61.          });
 62.    }
 63.
 64.    /**
 65.       A convenience method to add a component to given grid bag
 66.       layout locations.
 67.       @param c the component to add
 68.       @param gbc the grid bag constraints to use
 69.       @param x the x grid position
 70.       @param y the y grid position
 71.       @param w the grid width
 72.       @param h the grid height
 73.    */
 74.    public void add(Component c, GridBagConstraints gbc,
 75.       int x, int y, int w, int h)
 76.    {
 77.       gbc.gridx = x;
 78.       gbc.gridy = y;
 79.       gbc.gridwidth = w;
 80.       gbc.gridheight = h;
 81.       add(c, gbc);
 82.    }
 83.
 84.    /**
 85.       Finds the methods of the selected buddy.
 86.    */
 87.    public void findBuddyMethods()
 88.    {
 89.       int buddyIndex = buddyList.getSelectedIndex();
 90.       if (buddyIndex < 0) return;
 91.       Component buddy = buddies[buddyIndex];
 92.       propModel.removeAllElements();
 93.       try
 94.       {
 95.          BeanInfo info
 96.             = Introspector.getBeanInfo(buddy.getClass());
 97.          props = info.getPropertyDescriptors();
 98.          int j = 0;
 99.          for (int i = 0; i < props.length; i++)
100.          {
101.             Class propertyType = props[i].getPropertyType();
102.             if (int.class.equals(propertyType))
103.             {
104.                String name = props[i].getName();
105.                propModel.addElement(name);
106.                props[j++] = props[i];
107.             }
108.          }
109.       }
110.       catch(IntrospectionException e){}
111.    }
112.
113.    public Dimension getPreferredSize()
114.    {
115.       return new Dimension(300, 200);
116.    }
117.
118.    public void setObject(Object obj)
119.    {
120.       bean = (SpinBean)obj;
121.       BeanContext context
122.          = bean.getBeanContextProxy().getBeanContext();
123.       buddies = new Component[context.size()];
124.       buddyModel.removeAllElements();
125.       Iterator iter = context.iterator();
126.       int i = 0;
127.       while (iter.hasNext())
128.       {  Object buddy = iter.next();
129.          if (buddy instanceof Component)
130.          {  buddies[i] = (Component)buddy;
131.             String className = buddies[i].getClass().getName();
132.             buddyModel.addElement(className);
133.             i++;
134.          }
135.       }
136.    }
137.
138.    private SpinBean bean;
139.    private JList buddyList;
140.    private JList propList;
141.    private DefaultListModel buddyModel;
142.    private DefaultListModel propModel;
143.    private PropertyDescriptor[] props;
144.    private Component[] buddies;
145. }
Example 8-19 SpinBeanBeanInfo.java
 1. import java.awt.*;
 2. import java.beans.*;
 3.
 4. /**
 5.    The bean info for the chart bean, specifying the
 6.    customizer.
 7. */
 8. public class SpinBeanBeanInfo extends SimpleBeanInfo
 9. {
10.    public BeanDescriptor getBeanDescriptor()
11.    {
12.       return new BeanDescriptor(SpinBean.class,
13.          SpinBeanCustomizer.class);
14.    }
15. }
java.beans.Introspector

graphics/api.gif
 

java.beans.beancontext.BeanContextChild

graphics/api.gif
 

java.beans.beancontext.BeanContextChildSupport

graphics/api.gif
 

javax.beans.beancontext.BeanContextProxy

graphics/api.gif
 

javax.beans.beancontext.BeanContextServices

graphics/api.gif
 

javax.beans.beancontext.BeanContextServiceRevokedListener

graphics/api.gif
 

javax.beans.beancontext.BeanContextServiceRevokedEvent

graphics/api.gif
 

CONTENTS